如何遍历目录中的所有文件;如果它有子目录,我想遍历子目录中的文件

问题描述:

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"; 
      } 
    } 

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

您可以使用递归:定义,通过文件去,并呼吁本身的功能目录。然后调用顶层目录中的函数。请参阅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

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