2014-09-03 28 views
1

我遍歷所有文件以遞歸方式在某些目錄樹中獲得所需的文件,只要我得到的文件我做了一些操作,但在做操作之前,我需要檢查無論我對這個文件或不如果是那就不要再做一次進行操作否則繼續:無法找到它重複 - perl

但概率是,我無法找到來檢查條件:(

這裏是這樣的我的代碼:

use strict; 
use warnings; 
use autodie; 

use File::Find 'find'; 
use File::Spec; 
use Data::Printer; 

my ($root_path, $id) = @ARGV; 
our $anr_name; 
opendir my ($dh), $root_path; 
my @dir_list = grep -d, map File::Spec->catfile($root_path, $_), grep { not /\A\.\.?\z/ } readdir $dh; 
closedir $dh; 

my $count; 
for my $dir (@dir_list) { 
    find(
     sub { 
      return unless /traces[_d]*/; 
      my $file = $_; 
      my @all_anr; 
      #print "$file\n\n"; 
      my $file_name = $File::Find::name; 
      open(my $fh, "<", $file) or die "cannot open file:$!\n"; 
      my @all_lines = <$fh>; 
      my $i   = 0; 
      foreach my $check (@all_lines) { 
       if ($i < 10) { 
        if ($check =~ /Cmd line\:\s+com\.android\..*/) { 
         $anr_name = $check; 
         my @temp = split(':', $anr_name); 
         $anr_name = $temp[1]; 
         push(@all_anr, $anr_name); 
         #print "ANR :$anr_name\n"; 
         my $chk = check_for_dublicate_anr(@all_anr); 
         if ($chk eq "1") { 
          # performed some action 
         } 
        } 
        $i++; 
       } else { 
        close($fh); 
        last; 
       } 
      } 
     }, 
     $dir 
    ); 
} 

sub check_for_dublicate_anr { 
    my @anrname = @_; 
    my %uniqueAnr =(); 
    foreach my $item (@anrname) { 
     unless ($uniqueAnr{$item}) { 
      # if we get here, we have not seen it before 
      $uniqueAnr{$item} = 1; 
      return 1; 
     } 
    } 
} 
+0

可以與澄清你要在這裏完成的事。您是否需要檢查腳本的調用(例如保存狀態?)。是'check_for_dublicated_anr'和你試圖做到這一點的例子嗎?因爲這只是每次迭代測試'@ all_anr'的內容。但如果不是這樣,你可以在$ File :: Find :: name上使用類似的測試來清除重複的文件名。 – Sobrique 2014-09-03 10:28:59

+0

我正在遍歷所有文件以獲得所需的文件,然後在對該文件進行任何操作之前,我需要確保該操作僅在第一時間發生。說你需要提高缺陷跟蹤工具的一些錯誤,以便錯誤不應該提高重複我試圖實現這件事。 – user59053 2014-09-03 10:52:00

回答

1

您可以用Path::ClassPath::Class::Rule

use 5.010; 
use warnings; 
use Path::Class; 
use Path::Class::Rule; 

my $root = "."; 
my @dirs = grep { -d $_ } dir($root)->children(); 
my $iter = Path::Class::Rule->new->file->name(qr{traces[_d]*})->iter(@dirs); 

my $seen; 
while (my $file = $iter->()) { 
    for ($file->slurp(chomp => 1)) { 
     next unless /Cmd line:\s+(com\.android\.\S*)/; 
     do_things($file, $1) unless $seen->{$1}++; 
    } 
} 

sub do_things { 
    my ($file, $str) = @_; 
    say "new $str in the $file"; 
} 
+0

非常感謝jm666 :) – user59053 2014-09-03 12:29:35