我的脚本应该递归地检查所有包含的目录和文件的当前目录。然后应该输出每个文件和最后修改日期。
它似乎适用于当前目录中的某些目录,但不适用于其他目录。我得到的结果有偏差,并且不知道我的逻辑在哪里失败了。
#!/usr/bin/perl -w
use Cwd;
use Time::Piece;
my $startdir = &cwd;
my @files;
sub treeExamine() {
my $workdir = shift;
chdir($workdir) or die "Can't change directory\n";
opendir(DIR,".") or die "Can't open directory\n";
my @names = readdir(DIR) or die "Can't read directory\n";
closedir(DIR);
foreach my $name(@names) {
next if($name eq ".");
next if($name eq "..");
if(-f $name) {
my $dmod = (stat $name)[9];
my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($dmod);
$day = substr('0'.$mday,-2);
$month = substr('0'.($mon+1),-2);
$year = substr($year+1900,-2);
push (@files, "$name\t Modified on : $day/$month/$year\n");
}
else {
print "not file $name\n";
}
if(-d $name) {
&treeExamine($name);
next;
}
chdir($startdir) or die "Unable to change to directory $startdir \n";
}
}
&treeExamine(".");
print @files;
最佳答案
要递归遍历目录树,您应该使用 File::Find
。它是 Perl 5 中的核心模块。此外,您可以使用 Time::Piece
跳过尴尬的日期操作。
use strict;
use warnings;
use Time::Piece;
use File::Find;
find(\&wanted, ".");
sub wanted {
return if -d;
my $dmod = (stat $_)[9];
my $t = localtime($dmod);
print "$File::Find::name\t Modified on : ", $t->dmy("/"), "\n";
}
此代码将(我假设)执行您希望代码执行的操作,即扫描当前目录中的目录 "."
并打印所有文件的修改日期。预定义函数 dmy
不适用于 2 位数年份,但是如果不需要的话,为什么要创建 Y2K bug呢?想象一下日期 2011 年 11 月 11 日
。
此外,正如我在评论中提到的,您不应该使用 prototypes 。它们是可选的,其目的是为子例程提供额外的功能,以便模拟内置命令的某些行为(例如 map
和 grep
不带 sub
关键字的代码括号,或 pop
、shift
等(获取数组而不将其扩展到其元素)。你的子声明应该是
sub treeExamine {
没有别的。
关于Perl - 递归检查目录树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20414438/