2012-03-07 93 views
6
opendir(DIR,"$pwd") or die "Cannot open $pwd\n"; 
    my @files = readdir(DIR); 
    closedir(DIR); 
    foreach my $file (@files) { 
     next if ($file !~ /\.txt$/i); 
     my $mtime = (stat($file))[9]; 
     print $mtime; 
     print "\n"; 
    } 

基本上我想記下目錄中所有txt文件的時間戳。如果有一個子目錄我想在該子目錄中包含文件。如何遍歷目錄中的所有文件;如果它有子目錄,我想遍歷子目錄中的文件

有人可以幫我修改上面的代碼,以便它也包括子目錄。

如果我在Windows中使用下面的代碼的IAM這是在文件夾甚至我的文件夾以外的所有文件的獲取時間戳

my @dirs = ("C:\\Users\\peter\\Desktop\\folder"); 
    my %seen; 
    while (my $pwd = shift @dirs) { 
      opendir(DIR,"$pwd") or die "Cannot open $pwd\n"; 
      my @files = readdir(DIR); 
      closedir(DIR); 
      #print @files; 
      foreach my $file (@files) { 
        if (-d $file and !$seen{$file}) { 
          $seen{$file} = 1; 
          push @dirs, "$pwd/$file"; 
        } 
        next if ($file !~ /\.txt$/i); 
        my $mtime = (stat("$pwd\$file"))[9]; 
        print "$pwd $file $mtime"; 
        print "\n"; 
      } 
    } 

回答

8
use warnings; 
use strict; 

my @dirs = ("."); 
my %seen; 
while (my $pwd = shift @dirs) { 
     opendir(DIR,"$pwd") or die "Cannot open $pwd\n"; 
     my @files = readdir(DIR); 
     closedir(DIR); 
     foreach my $file (@files) { 
       if (-d $file and ($file !~ /^\.\.?$/) and !$seen{$file}) { 
         $seen{$file} = 1; 
         push @dirs, "$pwd/$file"; 
       } 
       next if ($file !~ /\.txt$/i); 
       my $mtime = (stat("$pwd/$file"))[9]; 
       print "$pwd $file $mtime"; 
       print "\n"; 
     } 
} 
+0

舊的堅固的方式......沒有遞歸很好地完成=) – Ouki 2012-03-07 11:44:12

+1

'$ file!〜/^\.*$/'是'$ file =〜/[^.]/'。但過去我因爲排除只有三個點或更長的名稱而被嚴厲譴責,因爲它們是Linux文件的有效名稱。所以測試*應該是'$ file!〜/^\.\.?$/' – Borodin 2012-03-07 12:05:53

+0

@perreal如果我想打開文件並在文件中搜索soome特定字符串並分離這些文件,我正在考慮這樣做打開輸入,$文件,然後$行= 然後seraching在它上,它是好的?或者還有其他一些簡單的方法 – Peter 2012-03-07 13:40:33

1

您可以使用遞歸:定義,通過文件去,並呼籲本身的功能目錄。然後調用頂層目錄中的函數。請參閱File::Find

+0

如何區分目錄中的文件和目錄 – Peter 2012-03-07 11:30:27

+1

@Peter:使用'-d'和'-f'運算符,記錄在[這裏](http://perldoc.perl.org/functions/- X.html) – Borodin 2012-03-07 12:09:16

11

File::Find是最適合這個。它是一個核心模塊,因此不需要安裝。此代碼的你彷彿心裏有

use strict; 
use warnings; 

use File::Find; 

find(sub { 
    if (-f and /\.txt$/) { 
    my $mtime = (stat _)[9]; 
    print "$mtime\n"; 
    } 
}, '.'); 

其中'.'是目錄樹的根要掃描的同等學歷;如果您願意,您可以在這裏使用$pwd。在該子例程中,Perl已經對發現該文件的目錄執行chdir,將$_設置爲文件名,並將$File::Find::name設置爲包含路徑的完全限定文件名。

+1

[並非所有人都會同意你](https://www.socialtext.net/perl5/alternatives_to_file_find)在File :: Find中是最好的。 – salva 2012-03-07 12:12:50

+1

File :: Find很慢,API令人沮喪,但我認爲它適合這樣的小事。我想聽聽有人反對。 – Borodin 2012-03-08 15:22:38

+0

@salva我知道很老的評論,但現在鏈接指向一個登錄頁面。 – 2016-10-19 16:08:22

相關問題