Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

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


Comment on RE: I don't use glob, I use readdir
Download Code
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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://15374]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (12)
As of 2014-10-22 13:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (118 votes), past polls