Bizarrer perl behavior with glob [duplicate]

[亡魂溺海] 提交于 2020-01-15 05:41:33

问题


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);

First glob is fine First in_function glob is fine Second glob is fine Second in_function glob fails Why do I need to assign glob to a variable when called within a function?


回答1:


From perldoc -f glob

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

The following will do the trick:

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

But you problably want to know what the matches are, so you can use

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


来源:https://stackoverflow.com/questions/25935585/bizarrer-perl-behavior-with-glob

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!