我非常喜欢perl新手,所以请耐心等待。
我一直在寻找一种方法来处理OS X中的文件夹,并遇到了这个解决方案:How to traverse all the files in a directory...
我稍微修改了perreal的答案(见下面的代码),以便我可以在参数中指定搜索文件夹;即我将my @dirs = (".");
更改为@dirs = ($ARGV[0]);
但由于某种原因,这不起作用 - 它会打开文件夹,但不会将任何子目录识别为文件夹,除了'。'和'..',所以它实际上从未超出指定的根目录。
如果我主动指定了文件夹(例如\ Volumes \ foo \ bar),它仍然无效。但是,如果我回到my @dirs = (".");
,然后坐在我想要的文件夹(foo \ bar)中并从自己的文件夹(foo \ boo \ script.pl)调用脚本,它可以正常工作。
这是'预期'行为吗?我错过了什么?!
非常感谢,
垫
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 :(得分:3)
问题是您在文件basename上使用-d
运算符而没有其路径。 Perl将在当前工作目录中查找该名称的目录,如果在那里找到一个目录,则返回true,它应该在$pwd
中查找。
此解决方案将$file
更改为始终保留文件或目录的全名,包括路径。
use strict;
use warnings;
my @dirs = (shift);
my %seen;
while (my $pwd = shift @dirs) {
opendir DIR, $pwd or die "Cannot open $pwd\n";
my @files = readdir DIR;
closedir DIR;
foreach (@files) {
next if /^\.\.?$/;
my $file = "$pwd/$_";
next if $seen{$file};
if ( -d $file ) {
$seen{$file} = 1;
push @dirs, $file;
}
elsif ( $file =~ /\.txt$/i ) {
my $mtime = (stat $file)[9];
print "$file $mtime\n";
}
}
}
答案 1 :(得分:0)
使用-d
的完整路径-d "$pwd/$file"