2012-07-02 70 views
1

因此,對於我正在編寫的程序,我想要做的是搜索目錄中的所有子目錄。如果子目錄名包含一個單詞,讓我們說「foo」,那麼程序將打開這個子目錄並對子目錄內的文件執行一個功能。任何人都可以給我一些關於如何去做這件事的幫助嗎?它也需要遞歸。在此先感謝Perl搜索特定的子目錄,然後處理

+0

File :: Find將執行您需要的遞歸搜索。 – TLP

回答

3

這可以使用File::Find模塊完成,但我認爲Path::Class是優越的,即使它不是核心模塊,並且可能需要安裝。

該程序找到想要的文件並調用process來處理它們。目前process子程序只是打印文件的名稱進行測試。

use strict; 
use warnings; 

use Path::Class; 

my $dir = dir '/path/to/root/directory'; 

$dir->recurse(callback => sub { 
    my $node = shift; 
    return if $node->is_dir; 
    my $parent = $node->parent; 
    if ($parent->basename =~ /foo/) { 
    process($node); 
    } 
}); 

sub process { 
    my $file = shift; 
    print $file, "\n"; 
} 

更新

如果你願意的話,這個程序執行使用File::Find相同的任務。

use strict; 
use warnings; 

use File::Find; 
use File::Basename qw/ basename /; 

my $dir = '/path/to/root/directory'; 

find(sub { 
    return unless -f; 
    if (basename($File::Find::dir) =~ /foo/) { 
    process($File::Find::name); 
    } 
}, $dir); 

sub process { 
    my $file = shift; 
    print $file, "\n"; 
} 

更新

按照要求,這裏是用Path::Class::Rule比較的進一步的解決方案。由於daxim建議代碼有點短。

use strict; 
use warnings; 

use Path::Class::Rule; 

my $rule = Path::Class::Rule->new; 
$rule->file->and(sub { $_->parent->basename =~ /foo/ }); 

my $next = $rule->iter('/path/to/root/directory'); 
while (my $file = $next->()) { 
    process($file); 
} 

sub process { 
    my $file = shift; 
    print $file, "\n"; 
} 
+0

你能否也請添加一個Path :: Class :: Rule解決方案作爲對比?代碼應該更短,更具說明性。 – daxim

+0

好的,如果我不能安裝任何模塊,我會怎麼做? – user1440061

+0

完美,非常感謝! – user1440061