我可以在数组中收集find(\& wanted,@ directory)的输出

时间:2014-02-19 17:58:25

标签: perl

我正在编写一个脚本,它将遍历目录(包括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”,一旦我在文件中获得此字符串,我必须将此当前文件推送到数组并开始读取另一个文件。

2 个答案:

答案 0 :(得分:4)

避免全球变量会更好。

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.
}

答案 1 :(得分:3)

@all_file的声明置于函数之外,并在find()完成后使用

my @all_file;
sub GetappropriateFile
{
  .. 
}

成功比赛后你也可以停止阅读文件,

if ($line =~ /Cmd\sline:\s+com.android*/) {
  push(@all_file, $file);
  last;
}
相关问题