【发布时间】:2014-11-14 03:31:31
【问题描述】:
use strict;
use warnings;
#only linux
#use diagnostics;
# - - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - - - -
sub in_function {
my $file = shift;
glob($file) or die ("$file file was not found\n"); #this fails second time called
# this is ok second time called
#my @dummy = glob($file) or die ("$file file was not found\n");
}
# - - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - - -
my $file = "/tmp/file1*.pdf";
glob($file) or die ("$file file was not found\n");
in_function($file);
$file = "/tmp/file2*.pdf";
glob($file) or die ("$file file was not found\n");
in_function($file);
第一个 glob 很好 第一个 in_function glob 很好 第二个glob很好 第二个 in_function glob 失败 为什么在函数中调用时需要将 glob 分配给变量?
【问题讨论】:
-
如果不使用返回值,
glob有什么用?glob or die不太可能是使用glob的有用方式。 -
似乎是检查通配符文件名是否存在的最简单方法。接受建议。
-
在某种程度上,这似乎是一个 XY 问题。就像一个解决方案在错误的方向上走得太远,你需要后退几步才能找到一个好的解决方案。首先,如果是我,我宁愿用循环检查确切的文件名,如果可能的话。并且检查文件名是否存在是检查您想要检查的任何事情是否发生的最佳方法?
glob可以给出文件存在的误报。例如,尝试从字符串中删除*,您会看到总是得到匹配。 -
@Paul:但它不检查是否存在通配符文件名。例如尝试
glob('{a,b}') -
@Borodin:没有误导;我假设这里的模式来自用户输入(或者为什么要验证它?)所以它需要是健壮的。我会做
() = grep -f, glob $pattern or die