在 Perl 中,您可以获得与模式匹配的文件列表:
my @list = <*.txt>;
print "@list";
现在,我想将模式作为变量传递(因为它已传递给函数)。但这不起作用:
sub ProcessFiles {
my ($pattern) = @_;
my @list = <$pattern>;
print "@list";
}
readline() on unopened filehandle at ...
有什么建议么?
在 Perl 中,您可以获得与模式匹配的文件列表:
my @list = <*.txt>;
print "@list";
现在,我想将模式作为变量传递(因为它已传递给函数)。但这不起作用:
sub ProcessFiles {
my ($pattern) = @_;
my @list = <$pattern>;
print "@list";
}
readline() on unopened filehandle at ...
有什么建议么?
使用glob:
use strict;
use warnings;
ProcessFiles('*.txt');
sub ProcessFiles {
my ($pattern) = @_;
my @list = glob $pattern;
print "@list";
}
以下是I/O Operators收到警告的原因的解释:
如果尖括号包含的是一个简单的标量变量(例如,$foo),那么该变量包含要输入的文件句柄的名称……直接调用内部函数为 glob($foo) 被认为更简洁,这可能是首先完成它的正确方法。)
为什么不将文件列表的数组引用传递给函数?
my @list = <*.txt>;
ProcessFiles(\@list);
sub ProcessFiles {
my $list_ref = shift;
for my $file ( @{$list_ref} ) {
print "$file\n";
}
}
use File::Basename;
@ext=(".jpg",".png",".others");
while(<*>){
my(undef, undef, $ftype) = fileparse($_, qr/\.[^.]*/);
if (grep {$_ eq $ftype} @ext) {
print "Element '$ftype' found! : $_\n" ;
}
}
用“eval”命令包装它怎么样?像这样...
sub ProcessFiles {
my ($pattern) = @_;
my @list;
eval "\@list = <$pattern>";
print @list;
}