所以我知道你可以在子程序中使用opendir打開目錄,然後使用readdir來讀取當前工作目錄中的所有文件,然後將所有文件推送到一個數組中。如果它是一個文件,則通過該數組,然後打印該文件或將該文件推入一個新數組,否則如果它是一個目錄,則遞歸地再次調用該子例程。我不明白的是在這裏指定深度。任何幫助是極大的讚賞。在Perl中如何使用遞歸來搜索目錄和子目錄並指定深度?
以下是我來到你的幫助的解決方案:
read_dir('test', 1);
sub read_dir {
$dir = shift;
$level = shift;
chdir ($dir);
opendir(DIR, '.') or die "Can't open $dir: $!";
@filesarray = readdir (DIR) or die;
closedir(DIR);
my @files;
foreach my $file (@filesarray) {
if (-f $file && $file =~ /\.txt$/i){
push @files, $file;
} ## end of if
elsif (-d $file) {
next if ($file eq ".");
next if ($file eq "..");
$dir = $file;
read_dir($dir, $level+1); ## QUESTION IS HERE?????
} ## end of elsif
} ## end of foreach
foreach my $file1 (@files) {
print "$file1\n";
}
} ## end of sub read_dir
相關問題:http://stackoverflow.com/q/13374829/133939 – Zaid