aconite has asked for the wisdom of the Perl Monks concerning the following question:

Greetings, I need to step through a directory structure and open a particular file that resides in particular subdirectories.

For instance, /web/web1/1234/config.pl
/web/web1/1235/config.pl
/web/web1/1236/config.pl

I need to step through, open config.pl, read some data from it, and then step to the next directory in the tree and do the same. Can anyone help me with some code for this?

TIA

  • Comment on Recurse through directories for file I/O

Replies are listed 'Best First'.
Re: Recurse through directories for file I/O
by tinman (Curate) on Mar 23, 2001 at 02:46 UTC

    I think File::Find is a module that you can use for this task..

    if not you can do it the harder way, as

    opendir(ROOT,'/web/web1/') or die "Can't open directory; @my_names = readdir(ROOT); # do a filetest(-d on each element of @my_names, # you can check directories thusly foreach my $elem(@my_names) { if(-d $elem) { # yup, its a directory } # push it onto a stack, for later processing else { # file, symlink.. so, check if its the file you <br>want to + process... and do stuff with it, or let it alone } }

    So, have this stuff inside a subroutine.. first open the header directory, and pass a list of elements to the subroutine.. keep doing this recursively for each subdirectory you encounter..
    HTH
    Update: I see YoungPups has already recommended File::Find.. sound advice :o)

Re: Recurse through directories for file I/O
by jeroenes (Priest) on Mar 23, 2001 at 02:46 UTC
    Hmmm... sounds a bit like homework. Sure we can help you. You need to read glob, and perldoc -f -e. That's all.

    Still not getting it?

    for my $dir (glob </web/web1/*>){ next unless -e my $conf = $dir.'/config.pl'; open DATA, $conf || die "Could not open $conf"; my @data = <DATA>; #and do something with it close DATA; }
    But as you have perl-files, you probably wanna do some do's. (do $conf)

    Jeroen
    "We are not alone"(FZ)

Re: Recurse through directories for file I/O
by YoungPups (Beadle) on Mar 23, 2001 at 02:41 UTC
    I'm a big fan of File::Find. Try checking that out...