Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

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 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?

Comment on read_dir issue
Select or Download Code
Re: read_dir issue
by moritz (Cardinal) on Aug 24, 2013 at 19:16 UTC
Re: read_dir issue
by fishmonger (Pilgrim) 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"; ##### } ##### }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1050826]
Approved by moritz
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (14)
As of 2014-08-01 14:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Who would be the most fun to work for?















    Results (25 votes), past polls