Question

I'm trying to traverse through all the subdirectories of the current directory in Perl, and get data from those files. I'm using grep to get a list of all files and folders in the given directory, but I don't know which of the values returned is a folder name and which is a file with no file extention.

How can I tell the difference?

Was it helpful?

Solution

You can use a -d file test operator to check if something is a directory. Here's some of the commonly useful file test operators

    -e  File exists.
    -z  File has zero size (is empty).
    -s  File has nonzero size (returns size in bytes).
    -f  File is a plain file.
    -d  File is a directory.
    -l  File is a symbolic link.

See perlfunc manual page for more

Also, try using File::Find which can recurse directories for you. Here's a sample which looks for directories....

sub wanted {
     if (-d) { 
         print $File::Find::name." is a directory\n";
     }
}

find(\&wanted, $mydir);

OTHER TIPS

print "$file is a directory\n" if ( -d $file );

Look at the -X operators:

perldoc -f -X

For directory traversal, use File::Find, or, if you're not a masochist, use my File::Next module which makes an iterator for you and doesn't require crazy callbacks. In fact, you can have File::Next ONLY return files, and ignore directories.

use File::Next;

my $iterator = File::Next::files( '/tmp' );

while ( defined ( my $file = $iterator->() ) ) {
    print $file, "\n";
}

# Prints...
/tmp/foo.txt
/tmp/bar.pl
/tmp/baz/1
/tmp/baz/2.txt
/tmp/baz/wango/tango/purple.txt

It's at http://metacpan.org/pod/File::Next

my @files = grep { -f } @all;
my @dirs = grep { -d } @all;
my $dh = opendir(".");
my @entries = grep !/^\.\.?$/, readdir($dh);
closedir $dh;

foreach my $entry (@entries) {
    if(-f $entry) {
        # $entry is a file
    } elsif (-d $entry) {
        # $entry is a directory
    }
}

It would be easier to use File::Find.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top