我想在目录和子目录中列出该文件。我使用perl文件::查找。我有可能将结果存储到数组中吗?
这是代码
use warnings;
use strict;
use File::Find;
my $location="tmp";
sub find_txt {
my $F = $File::Find::name;
if ($F =~ /txt$/ ) {
push @filelist, $F;
return @filelist;
}
}
my @fileInDir = find({ wanted => &find_txt, no_chdir=>1}, $location);
print OUTPUT @fileInDir
上面的代码不显示输出
当然,只需在外面声明的数组中push
:
use warnings;
use strict;
use File::Find;
my $location = "tmp";
my @results;
my $find_txt = sub {
my $F = $File::Find::name;
if ($F =~ /txt$/ ) {
push @results, $F;
}
};
find({ wanted => $find_txt, no_chdir=>1}, $location);
for my $result (@results) {
print "found $resultn";
}
wanted
回调的返回值被忽略。find
本身也没有记录或有用的返回值。
对于后代,这对Path :: Iterator :: Rule。
来说更为简单use strict;
use warnings;
use Path::Iterator::Rule;
my $location = 'tmp';
my $rule = Path::Iterator::Rule->new->not_dir->name(qr/txt$/);
my @paths = $rule->all($location);
替换
my @fileInDir = find({ wanted => &find_txt, no_chdir=>1}, $location);
my @fileInDir;
find({ wanted => sub { push @fileInDir, find_txt(); }, no_chdir=>1 }, $location);
并添加缺失
return;
又名
return ();
到find_txt
。与早期答案中的解决方案不同,这使您可以重复使用且位置方便的"通缉"潜艇。