Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I recursively read out directories in Perl?

I want to read out a directory recursively to print the data-structure in an HTML-Page with Template::Toolkit. But I'm hanging in how to save the Paths and Files in a form that can be read our easy.

My idea started like this

sub list_dirs{

     my ($rootPath) = @_;
     my (@paths);

     $rootPath .= '/' if($rootPath !~ /\/$/);

     for my $eachFile (glob($path.'*'))
     {

         if(-d $eachFile)
         {
              push (@paths, $eachFile);

              &list_dirs($eachFile);
          }
          else
          {
              push (@files, $eachFile);
          }
     }

 return @paths;
}

How could I solve this problem?

like image 960
Przemek Avatar asked Mar 19 '10 09:03

Przemek


People also ask

How do I read all files in a directory in Perl?

This shows one way of prepending: $dir = "/usr/local/bin"; print "Text files in $dir are:\n"; opendir(BIN, $dir) or die "Can't open $dir: $!"; while( defined ($file = readdir BIN) ) { print "$file\n" if -T "$dir/$file"; } closedir(BIN);

Does Perl support recursion?

Perl provides us with the flexibility to use subroutines both iteratively and recursively. A simple example showing the use of recursive subroutine in Perl would be that calculating the factorial of a number.


1 Answers

You should always use strict and warnings to help you debug your code. Perl would have warned you for example that @files is not declared. But the real problem with your function is that you declare a lexical variable @paths on every recursive call to list_dirs and don't push the return value back after the recursion step.

push @paths, list_dir($eachFile)

If you don't want to install additional modules, the following solution should probably help you:

use strict;
use warnings;
use File::Find qw(find);

sub list_dirs {
        my @dirs = @_;
        my @files;
        find({ wanted => sub { push @files, $_ } , no_chdir => 1 }, @dirs);
        return @files;
}
like image 98
mdom Avatar answered Sep 28 '22 12:09

mdom