http://www.perlmonks.org?node_id=1050826

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

I am using Strawberry perl on Win7 (64-bit) and have an issue with read_dir. The simple code:

use strict; use warnings; use File::Slurp; my @files; # Array of all file names in the folder. if($ARGV[0]) { @files = read_dir($ARGV[0]); } else { @files = read_dir("."); } for my $file (@files) { print $file; if(-f $file) { print " is a file.\n"; } else { print " is a dir.\n"; } }

The file structure used for test:

file1.txt filetest.pl folder -> file2.txt file3.txt

Running this on current (working) dir, gives correct output:

file1.txt is a file. filetest.pl is a file. folder is a dir.

but when providing folder as argument, the files in it are not recognized as files:

file2.txt is a dir. file3.txt is a dir.
What am I missing?

Replies are listed 'Best First'.
Re: read_dir issue
by moritz (Cardinal) on Aug 24, 2013 at 19:16 UTC
Re: read_dir issue
by fishmonger (Chaplain) on Aug 24, 2013 at 20:39 UTC

    You could/should add the "prefix" option in the read_dir statement so that the path will be prepended to the filename.

    @files = read_dir($ARGV[0], prefix => 1);

    EDIT:
    I'd probably reduce your code a little, like this:

    my $path = $ARGV[0] || '.'; my @files = read_dir($path, prefix => 1); for my $file (@files) { say -f $file ? "$file is a file" : "$file is a dir"; }
Re: read_dir issue
by zork42 (Monk) on Aug 26, 2013 at 07:59 UTC
    BUG: folders can contain things other than files and folders.
    I'm pretty sure this is true even in Windows.
    eg when I do dir C:\Users, I see <DIR>s, but also <SYMLINKD>s and <JUNCTION>s (Windows Vista)
    See file test ops

    So you might want to change lines 16-27 in your OP, as indicated by ##### in the following:
    for my $file (@files) { print $file; if(-f $file) { print " is a file.\n"; } #else ##### elsif (-d _) ##### { print " is a dir.\n"; } else ##### { ##### print " is something else.\n"; ##### } ##### }