Solved

make an array of a directory tree/files paths in perl

Posted on 2009-04-05
5
733 Views
Last Modified: 2012-06-27
I am looking (without installing extra packages) to get an array to have a directory structure  of a bunch of folders then go through each folder and list the files, (and also know the directory its in)

Take the following file paths (starting from 'My Photos' for instance):

/home/tim/my photos/
/home/tim/my photos/journey/1.jpg
/home/tim/my photos/journey/2.jpg
/home/tim/my photos/journey/3.jpg
/home/tim/my photos/birthday/1.jpg
/home/tim/my photos/birthday/2.jpg
/home/tim/my photos/birthday/3.jpg

I would like to find the code that makes me an array of the directorys (recursively) in a given path - in the above example I would like @dirs = ("/home/tim/my photos/journey/" , "/home/tim/my photos/birthday/")

Then I want to get the full file paths into another array...  so @files = ("/home/tim/my photos/journey/1.jpg","/home/tim/my photos/journey/2.jpg", "/home/tim/my photos/journey/3.jpg"....

I know this should be easy but I can't find a straightforward approach, I don't wish to have it rely on other packages as it has to run from different web servers which won't let me install extra packages from CPAN etc.
0
Comment
Question by:timbo007
  • 2
  • 2
5 Comments
 
LVL 40

Accepted Solution

by:
mrjoltcola earned 150 total points
ID: 24071521
Hope this gets you startred.
#!/usr/bin/perl
 

use strict;

use File::Find;

my @files;
 

find( \&handleFile, '/home' );
 

# Print out sorted list if desired...

#print sort @files;
 
 

sub handleFile() {
 

   if(-d) {

      # Print each file and store into list as we go

      print "$File::Find::name\n";

      push @files, $File::Find::name;

   }
 

}

Open in new window

0
 
LVL 3

Assisted Solution

by:WeiXi
WeiXi earned 100 total points
ID: 24071745
This works without any extra package. It is rather straight-forward, anyway.
my $root = '/home/tim/my photos';

my @dirs;

my @jpgs;
 

sub recurse {

    my $base = shift;

    push @dirs, $base;

    opendir(my $DIR, $base) || die "can't opendir $base: $!";

    my @dircontents = readdir $DIR;

    closedir $DIR;

    push @jpgs, grep { /\.je?pg$/i && -f $_ } map {"$base/$_"} @dircontents;

    recurse("$base/$_") foreach grep { /[^.]/ && -d "$base/$_" } @dircontents;

}
 

recurse $root;

Open in new window

0
 

Author Comment

by:timbo007
ID: 24071912
Both answers worked for me, but the first answer by mrjoltcola was easier to implement into my own program. However the second one doesn't use any other packages at all! luckily File::find seems to be installed by default :)

I don't quite understand whats going on the last part of the recurse sub (at row 12) on the second example as that seems outside what I know, do you have the time to elaborate on what it means for me ?

cheers!!
    recurse("$base/$_") foreach grep { /[^.]/ && -d "$base/$_" } @dircontents;

Open in new window

0
 
LVL 3

Expert Comment

by:WeiXi
ID: 24071936
/[^.]/
Match only strings with at least one character that's not a dot. This is to prevent an infinite loop into directory '.'

-d "$base/$_"
Returns true if "$base/$_" is a directory, other wise false.

grep { /[^.]/ && -d "$base/$_" } @dircontents
Filter all entries in the current directory that are directores themselves, but not '.' and '..'

foreach grep { /[^.]/ && -d "$base/$_" } @dircontents
Iterate over all those filtered directories...

recurse("$base/$_") foreach grep { /[^.]/ && -d "$base/$_" } @dircontents;
...and iteratively call the recurse function with the filtered directories as arguments.
0
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24072657
Curious why you graded with a B since you did not ask for clarification before closing the question?
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
PERL get the value for query 4 145
PERL variable conundrum 9 89
Perl Script to read file contents, make changes, and build new file 7 90
Control Number of Log Files -Perl 7 55
On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now