加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:15:50 所属栏目:大数据 来源:网络整理
导读:opendir(DIR,"$pwd") or die "Cannot open $pwdn"; 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文件
opendir(DIR,"$pwd") or die "Cannot open $pwdn";
    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中使用下面的代码我获取文件夹中所有文件的时间戳,甚至在我的文件夹之外

my @dirs = ("C:UserspeterDesktopfolder");
    my %seen;
    while (my $pwd = shift @dirs) {
            opendir(DIR,"$pwd") or die "Cannot open $pwdn";
            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 $pwdn";
        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 $mtimen";
        }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读