在Perl中如何使用递归来搜索目录和子目录并指定深度? [英] In Perl how to use recursion to search directories and sub directories and specify the depth?
问题描述
以下是我帮助您解决的问题:
read_dir('test',1);
sub read_dir {
$ dir = shift;
$ level = shift;
chdir($ dir);
opendir(DIR,'。')或死无法打开$ dir:$!;
@filesarray = readdir(DIR)或死亡;
closedir(DIR);
我的@files;
foreach我的$文件(@filesarray){
if(-f $ file&& $ file =〜/\.txt$/i){
push @files,$文件;
} ##如果
elsif(-d $ file){
next if($ file eq。);
next if($ file eq..);
$ dir = $ file;
read_dir($ dir,$ level + 1); ##问题在这里
} ## end of elsif
} ## end of foreach
foreach我的$ file1(@files){
print$ file1\\\
;
}
} ## sub read_dir的结尾
您可以将参数传递给调用的递归函数,例如级别
,并将函数调用为 recurse(level + 1,子目录)
。
无论如何,最好使用像 File :: Find
为此任务。
So I know you can in the subroutine, open the directory using opendir, then use readdir to to read all the files in the current working directory, then push all the files into an array. Go through the array if it is a file then print the file or push that file into a new array else if it is a directory recursively call the subroutine again. What I don't understand is where in here would I specify the depth. Any help is greatly appreciated.
The following is the solution I arrived at with your help:
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
You can pass a parameter to the recursing function called, say, level
, and call the function as recurse(level+1, subdirectory)
.
Anyway, it's best to use a specialized library like File::Find
for this task.
这篇关于在Perl中如何使用递归来搜索目录和子目录并指定深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!