Perl - 递归检查目录树

标签 perl recursion directory

我的脚本应该递归地检查所有包含的目录和文件的当前目录。然后应该输出每个文件和最后修改日期。

它似乎适用于当前目录中的某些目录,但不适用于其他目录。我得到的结果有偏差,并且不知道我的逻辑在哪里失败了。

#!/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 。它们是可选的,其目的是为子例程提供额外的功能,以便模拟内置命令的某些行为(例如 mapgrep不带 sub 关键字的代码括号,或 popshift 等(获取数组而不将其扩展到其元素)。你的子声明应该是

sub treeExamine {

没有别的。

关于Perl - 递归检查目录树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20414438/

相关文章:

Perl 异或返回意外结果

c++ - 用 C++ 编写递归函数的最佳方法?

php - 访问数据库

file - 比较 CMD 中不相同文件的两个文件夹

algorithm - 如何在递归调用中获取路径

r - 快速测试目录是否为空

perl - 使用 Apache 和 Perl 进行服务器推送的机制

linux - 如何将多列中的数字排序或重新排列为多行[固定为 4 列]?

regex - perl - 如何使用 RegEx 获取所有相似的匹配子字符串

c++ - 用4递归函数替换奇数位