2013-02-19 8 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 
} 
관련 문제