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中使用下面的代码我获取文件夹中所有文件的时间戳,甚至在我的文件夹之外
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) { 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"; } }