2013-02-19 17 views
2

我是Perl新手,正在努力學習語言,但在做一些我認爲可能很簡單的工作時遇到困難。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"; 

誰能幫助我加強這方面的代碼遞歸搜索任何子目錄呢?

回答

2

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 
}