Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Diff between file and directory

by chuleto1 (Beadle)
on Aug 25, 2003 at 17:25 UTC ( [id://286424]=perlquestion: print w/replies, xml ) Need Help??

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

Monks,
When reading a a directory, I would like to differentiate between a file and directory. Read Comment below....
@return_files = readDirectory($directory); foreach(@return_files) { next if ($_ eq "." || $_ eq ".."); ####################### #How can a tell between files and directories? ######################## print OUT "<ul> <li id=\"foldheader\">$_</li>"; print OUT "</ul>"; } sub readDirectory { opendir DIR, $directory; @files = readdir(DIR); return @files; closedir(DIR); }
Any suggestions

Replies are listed 'Best First'.
Re: Diff between file and directory
by allolex (Curate) on Aug 25, 2003 at 17:39 UTC

    You're probably looking for the -d and -f file test operators. There is a discussion of them in the Camel Book section 1.5.7.

    print "this is a file\n" if -f; print "this is a directory\n" if -d;

    You might prefer to use a module like File::Find instead. It has all of your logic built into it already.

    Hope that helps.

    --
    Allolex

      you could also try and open the directory. if it succeeds close it. I used this is a recursive function for mapping drive contents to a logfile.

      ie
Re: Diff between file and directory
by bear0053 (Hermit) on Aug 25, 2003 at 17:34 UTC
    the following test will determine if the array element is a a directory in windows
    if (-d $file)
    make sure $file contains path as well as file/directory name. this will check if it is a readable file
    if (-e $file)

      the following test will determine if the array element is a a directory in windows

      I heard this works on all other platforms as well. ;)

      --
      Allolex

Re: Diff between file and directory
by Fletch (Bishop) on Aug 25, 2003 at 17:37 UTC

    perldoc -f -X, perldoc -f stat

Re: Diff between file and directory
by vek (Prior) on Aug 26, 2003 at 04:11 UTC

    Just a quick comment on your code. Always check to make sure opendir was successful:

    opendir (DIR, $directory) || do { # your error handling here... };
    -- vek --

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://286424]
Approved by VSarkiss
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-04-24 20:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found