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

Pet*_*ter 8 perl directory-traversal

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";
    }
Run Code Online (Sandbox Code Playgroud)

基本上我想要记下目录中所有txt文件的时间戳.如果有一个子目录,我也想在该子目录中包含文件.

有人可以帮我修改上面的代码,以便它也包含子目录.

如果我在windows中使用下面的代码我获取文件夹中所有文件的时间戳,甚至在我的文件夹之外

 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";
            }
    }
Run Code Online (Sandbox Code Playgroud)

Bor*_*din 14

File :: Find最适合这个.它是一个核心模块,因此不需要安装.此代码与您似乎想到的相同

use strict;
use warnings;

use File::Find;

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

哪个'.'是要扫描的目录树的根目录; $pwd如果你愿意,你可以在这里使用.在子例程中,Perl已经chdir找到了找到文件的目录,$_设置了文件名,并$File::Find::name设置为包含路径的完全限定文件名.


per*_*eal 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) {
                next if $file =~ /^\.\.?$/;
                my $path = "$pwd/$file";
                if (-d $path) {
                        next if $seen{$path};
                        $seen{$path} = 1;
                        push @dirs, $path;
                }
                next if ($path !~ /\.txt$/i);
                my $mtime = (stat($path))[9];
                print "$path $mtime\n";
        }
}
Run Code Online (Sandbox Code Playgroud)