Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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

by t0mas (Priest)
on May 30, 2000 at 13:46 UTC ( [id://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 (Patriarch) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://15374]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-03-28 20:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found