Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

read_dir issue

by snowlight (Initiate)
on Aug 24, 2013 at 19:11 UTC ( #1050826=perlquestion: print w/replies, xml ) Need Help??
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 folder -> file2.txt file3.txt

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

file1.txt is a file. 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);

    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"; ##### } ##### }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1050826]
Approved by moritz
Front-paged by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2017-10-18 04:55 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (242 votes). Check out past polls.