如何遍历目录中的所有文件;如果它有子目录,我想遍历子目录中的文件
问题描述:
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";
}
}
答
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
设置为包含路径的完全限定文件名。
旧的坚固的方式......没有递归很好地完成=) – Ouki 2012-03-07 11:44:12
'$ file!〜/^\.*$/'是'$ file =〜/[^.]/'。但过去我因为排除只有三个点或更长的名称而被严厉谴责,因为它们是Linux文件的有效名称。所以测试*应该是'$ file!〜/^\.\.?$/' – Borodin 2012-03-07 12:05:53
@perreal如果我想打开文件并在文件中搜索soome特定字符串并分离这些文件,我正在考虑这样做打开输入,$文件,然后$行= 然后seraching在它上,它是好的?或者还有其他一些简单的方法 – Peter 2012-03-07 13:40:33