Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Reading entire subfolder tree into an array

by SuperCruncher (Pilgrim)
on May 28, 2002 at 16:48 UTC ( [id://169827]=note: print w/replies, xml ) Need Help??


in reply to Reading entire subfolder tree into an array

Well, here's an idea:
my $dir = '/home/user1'; my @files = glob("$dir/*"); # Get list of files my @directories = grep { -d } @files; # Use -d to get dirs
Then you could do:
foreach my $directory (@directories) { my @list = glob("$directory/*"); }
...and of course repeat the process until a directory contains no more directories. Probably an easier way of traversing a directory structure is using the File::Find module though it does have some very irritating behaviours... It's a "standard" Perl module, and it should be on your system already.

Replies are listed 'Best First'.
Re^2: Reading entire subfolder tree into an array
by Aristotle (Chancellor) on May 28, 2002 at 17:23 UTC
    Actually I strongly advise using File::Find instead. There's too much to think of when you roll your own: what happens if you run into symlinks for example? Perl standard and CPAN modules for seemingly simple tasks are there for a reason.

    Makeshifts last the longest.

      Based on all your input, I have spent the last few hours readin up on find::file and believe it is the best way to go. However, i do have one remaining question.

      First, herre is my code I have come up with:

      use File::Find; finddepth (\&RetrieveAll, "c:\\fpx"); sub RetrieveAll { push (@list,$_,"\n"); }

      How do I get $_ to include the absolute path of the file? $_ lists the folder name, then all files within it... i'd rather have the absolute path.

      Is this simple?

      Please advise
      Simon
        perldoc File::Find says:
        The wanted() function does whatever verifications you want.
        $File::Find::dir contains the current directory name, and $_ the current filename within that directory. $File::Find::name contains the complete pathname to the file.
        Btw - what's that "\n" do there in the push()? :-)
        ____________

        Makeshifts last the longest.
        Hi Simon, you just have to use the module variable $File::Find::name instead of $_. It's as easy as that. So your code will look like

        use File::Find; finddepth (\&RetrieveAll, "c:\\fpx"); sub RetrieveAll { push (@list,$File::Find::name,"\n"); }

        HTH

        weini

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-19 04:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found