Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

RE: I don't use glob, I use readdir

by t0mas (Priest)
on May 30, 2000 at 13:46 UTC ( #15374=note: print w/replies, xml ) Need Help??

in reply to I don't use glob, I use readdir
in thread Getting a List of Files Via Glob

I often use readdir in a recursive mode, like :
&makeTree(0,'/where/to/start'); sub makeTree { my ($level,$Dir)=@_; # Get all directories opendir(DIR,$Dir) || die "$!"; my @Dirs = grep { /^[^.].*/ && -d "$Dir/$_" } readdir(DIR); closedir(DIR); # Read files and do stuff or whatever... # Call self foreach my $currDir (@Dirs) { &makeTree($level+1,join('/',$Dir,$currDir)); } };

/brother t0mas

Replies are listed 'Best First'.
Descending through directories
by Corion (Pope) on May 30, 2000 at 15:12 UTC
    In your code, you donīt need to re-read the directory to get at the files in the directory - although it would be difficult to "compute" the difference of the array elegantly (well, difficult to me at least). I mostly use the following way, intermixing files and directories :
    # Untested code - use at your own risk sub handledirectory { my ($directory) = @_; my ($entry, @direntries); opendir( DIR, $directory ) or die "Canīt read $directory : $!\n"; @direntries = readdir( DIR ) or die "Error reading $directory : $! +\n"; closedir DIR; foreach $entry, @direntries { # File::Spec gives us cross-platform path utilities # and comes with every Perl standard distribution require File::Spec; my $fullpath; # skip current and parent directory entries next if $entry =~ /^\.\.?$/; $fullpath = File::Spec->catfile( $directory, $entry ); if (-d $fullpath ) { &handledirectory($fullpath); } elsif ( -f $fullpath ) { # This second call to stat() (implicit in the "-f") # could be done away by using some other short # variable that does caching, but that would maybe # confuse the readers ... ... do stuff ... } else { # something strange ... }; }
      The code I posted was to demonstrate a way to recursive call self, not being very useful in itself... ;-)
      There is more than one way to do it. You could rewinddir and readdir again (with a different grep) on the same handle too..
      But I agree that your solution is beautiful.
      Maybe someone could benchmark some testcases.

      /brother t0mas
        I've never used perlfunc:rewinddir() :), and my post wasn't meant as an offence, sorry if I came across that way ...

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://15374]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2017-05-28 07:09 GMT
Find Nodes?
    Voting Booth?