【问题标题】:Perl - enhance code to recursively count filesPerl - 增强代码以递归计算文件
【发布时间】:2013-02-20 05:05:04
【问题描述】:

我是 Perl 的新手,我正在努力学习这门语言,但在做一些我认为可能很简单的事情时遇到了困难。

我已经能够使脚本正常工作,该脚本将仅计算目录中的文件数。我想增强脚本以递归计算任何子目录中的所有文件。我已经搜索并找到了 GLOB 和 File::Find 的几个不同选项,但无法让它们工作。

我当前的代码:

#!/usr/bin/perl
use strict;
use warnings;

use Path::Class;

# Set variables

my $count = 0;  # Set count to start at 0
my $dir = dir('p:'); # p/

# Iterate over the content of p:pepid content db/pepid ed
while (my $file = $dir->next) {   


    next if $file->is_dir();    # See if it is a directory and skip


    print $file->stringify . "\n";   # Print out the file name and path
    $count++   # increment count by 1 for every file counted

}


print "Number of files counted " . $count . "\n";

谁能帮我增强此代码以递归搜索任何子目录?

【问题讨论】:

    标签: perl


    【解决方案1】:

    File::Find 模块是递归操作的好朋友。这是一个计算文件的简单脚本:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use Cwd;
    use File::Find;
    
    my $dir = getcwd; # Get the current working directory
    
    my $counter = 0;
    find(\&wanted, $dir);
    print "Found $counter files at and below $dir\n";
    
    sub wanted {
        -f && $counter++; # Only count files
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多