Search code examples
perlrecursiondirectorysubdirectorydepth

In Perl how to use recursion to search directories and sub directories and specify the depth?


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

Solution

  • 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.