在Perl中如何使用递归来搜索目录和子目录并指定深度? [英] In Perl how to use recursion to search directories and sub directories and specify the depth?

查看:487
本文介绍了在Perl中如何使用递归来搜索目录和子目录并指定深度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道你可以在子程序中,使用opendir打开目录,然后使用readdir来读取当前工作目录中的所有文件,然后将所有文件推入数组。如果它是一个文件,然后打印文件或将该文件推送到一个新数组中,如果它是一个目录,则再次递归地调用该子程序,则通过该数组。我不明白的是我在这里指定深度。任何帮助是极大的赞赏。






以下是我帮助您解决的问题:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆