perl - 奇怪的 perl 行为与 glob

标签 perl list glob

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 没问题 第二个球没问题 第二个 in_function glob 失败 为什么在函数内调用时需要将 glob 分配给变量?

最佳答案

来自perldoc -f glob

In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted.

下面的方法可以解决这个问题:

() = glob($file) 
   or die ...;

但是您可能想知道匹配项是什么,因此您可以使用

my @matches = glob($file) 
   or die ...;

关于perl - 奇怪的 perl 行为与 glob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25935585/

相关文章:

python - Glob 查找目录中及目录下的文件

arrays - nullglob 和数组

powershell - 如何让 PowerShell 很好地处理文件名中的 [ 或 ] ?

perl - 如何降级到perl 5.10.1?

C 段错误 - 链表

c# - 从 Dictionary<string, List<string>> 中检索值

list - 如何制作一个新列表指向其他地方,Lisp

perl - 为什么在 Perl chmod 中使用 int()?

perl - 如何使用拆分值拆分数据?

perl - LWP::Protocol::https::Socket: 连接:超时错误