我正在编写一个脚本,该脚本将遍历目录(还包括subdir)并将所需的文件推送到数组中,以便我可以处理每个文件。
这是我的代码:
use strict;
use warnings;
use File::Find;
my $path = $ARGV[0];
find({ wanted => \&GetappropriateFile }, $path);
sub GetappropriateFile
{
my $file = $_;
my @all_file;
# print "$file\n";
if ( -f and /traces[_d+]/)
{
#print "$file\n";
open(my $fh, "<", $file) or die "cannot open file:$!\n";
while( my $line = <$fh>){
$line =~ /Cmd\sline:\s+com.android*/;
push(@all_file,$file);
#print "$file\n";
}
close($fh);
#print"@all_file\n";
}
}
问题区域:我的$ file = $ _;
如果我可以在这里使用数组而不是使用“ $ file”,那么我可以轻松地逐个读取这些文件并进行过滤。
在这里,我正在努力做的是:我必须打开每个文件,并在获取文件中的字符串后立即检查字符串“ Cmd line:com.android”,我必须将当前文件推送到数组中并开始读取另一个文件。
最佳答案
最好避免使用全局变量。
use strict;
use warnings;
use File::Find qw( find );
sub IsAppropriateFile {
my ($file) = @_;
if (-f $file && $file =~ /traces[_d+]/) {
open(my $fh, "<", $file) or die "cannot open file:$!\n";
while ( my $line = <$fh> ) {
if ($line =~ /Cmd\sline:\s+com.android*/) {
return 1;
}
}
}
return 0;
}
{
my $path = $ARGV[0];
my @matching_files;
find({
wanted => sub {
push @matching_files, $_ if IsAppropriateFile($_);
},
}, $path);
print("$_\n") for @matching_files; # Or whatever.
}
关于perl - 我可以在数组中收集find(\&wanted,@directories)的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21888566/