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

标签 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”,我必须将当前文件推送到数组中并开始读取另一个文件。

最佳答案

最好避免使用全局变量。

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/

相关文章:

python - 通过主机名解析mac地址

javascript - 从 Web UI 与本地 Perl 脚本交互

perl - vim 的正确 perl 路径

linux - 在命令行中运行三个程序,或者在程序运行时记录 CPU 使用率的脚本

perl - 从计划任务运行 perl Plackup 脚本

perl - 使用 curl 解析 XML,获取图像的 URL 并下载它

regex - Perl 中前导空格的匹配和计数

Perl INT 处理程序和 Bash STDERR 重定向

java - 支持 vector 机简介

regex - 大文件中带有反向引用的多行搜索