glob的奇怪perl行为

glob的奇怪perl行为,perl,list,glob,Perl,List,Glob,第一个球很好 第一个in_函数glob很好 第二个球很好 第二个in_函数glob失败 在函数中调用时,为什么需要将glob赋值给变量?From 在标量上下文中,glob迭代此类文件名扩展,当列表用尽时返回unde 以下内容将实现此目的: use strict; use warnings; #only linux #use diagnostics; # - - - - - - - - - - - -- - - - - - - - - - - - - - - - - - - - - - - su

第一个球很好 第一个in_函数glob很好 第二个球很好 第二个in_函数glob失败 在函数中调用时,为什么需要将glob赋值给变量?

From

在标量上下文中,glob迭代此类文件名扩展,当列表用尽时返回unde

以下内容将实现此目的:

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($file) 
   or die ...;

如果不使用返回值,
glob
有什么用处
glob或die
不太可能是使用
glob
的有用方法。这似乎是检查是否存在通配符文件名的最简单方法。接受建议。在某种程度上,这似乎是一个XY问题。就像一个在错误方向上走了一步的解决方案,你需要后退几步才能找到一个好的解决方案。首先,如果是我,我宁愿用循环检查确切的文件名,如果可能的话。检查文件名是否存在是检查您想要检查的内容是否已发生的最佳方法
glob
可能会给出文件存在的假阳性。例如,尝试从字符串中删除
*
,您将看到始终有一个匹配项。@Paul:但它不会检查是否存在通配符文件名。请尝试
glob({a,b}')
instance@Borodin:不具误导性;我假设这里的模式来自用户输入(或者为什么要验证它?),所以它需要健壮。当调用glob()或die时,我会执行
()=grep-f,glob$pattern或die
,这是函数中的上下文?当这样调用:glob()或die时,这是不在函数中的上下文吗?@Paul在这两种情况下都是标量上下文。请注意,在标量上下文中对glob的第一次调用将启动iterator.P.S。()=glob($file)将其更改为列表上下文?@Paul:函数与否没有区别,但源中的每个glob运算符都是一个单独的迭代器,因此除非以某种方式循环返回,否则不会看到问题。@amphetamachine
my @matches = glob($file) 
   or die ...;