in reply to Recursive Directory Listings

First, it doesn't appear that you're actually doing anything with the File::stat module other than including it in your program. The -d file test is part of Perl; you don't need a module to use it.

Next, you've fallen prey to the "readdir() returns unqualified names" problem. readdir() is only returning the name of the entries in the directory -- you must prepend the PATH to those names:

my $dir = ...; opendir my $dh, $dir or die "can't read $dir: $!"; while (defined(my $name = readdir $dh)) { my $file = "$dir/$name"; # XXX <-- here if (-d $file) { ... } } closedir $dh;
Note the line I've commented: I'm combining the directory and the name to make a filename that is meaningful.

Lastly, your code only goes one level down. To get indefinite depth, you'll need a recursive solution, but you should consider the File::Find module which does this for you.


Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart

Replies are listed 'Best First'.
Re^2: Recursive Directory Listings
by ikegami (Patriarch) on Sep 06, 2005 at 17:18 UTC
    To get indefinite depth, you'll need a recursive solution

    Not quite. You simply need a stack. Recursion is just one way of obtaining a stack. What follows is another:

    my @to_visit = $base_dir; while (@to_visit) { my $dir = pop(@to_visit); opendir(my $dh, $dir) or ...; my $file; while(defined($file = readdir($dh))) { next if $file eq '.'; next if $file eq '..'; # Should use File::Spec. $file = "$dir/$file"; if (-d $file) { push(@to_visit, $file); } else { ... } } }

    Substitute pop with shift if you want to process the tree breadth first.