Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: File handling basics

by vinoth.ree (Monsignor)
on Jul 17, 2015 at 10:07 UTC ( [id://1135136]=note: print w/replies, xml ) Need Help??


in reply to File handling basics

Include $! in die part of open(),It will give you the reason, why it can not open the file.

Note that the file names in $file do not include the full path and do include "." and ".." which you probably don't care to have. You can eliminate them with,

@FILES=grep(!/^\.\.?}$/, readdir(DIR));

The regular expression used in the grep can be extended to filter all sorts of ways, returning only files with a specific extension or starting with some text,etc.

To check for all the subdirectories in a directory, try code like this:

$path = shift; $path = "." unless $path; opendir( DIR, $path ) or die "Can't open $path: $!"; while ( $entry = readdir( DIR ) ) { $type = ( -d "$path\\$entry" ) ? "dir" : "file"; # $path is cr +ucial! print "$type\t$entry\n"; } closedir( DIR );

It's a common mistake to leave out the $path from the -d check. If you do this, perl thinks you're talking about files in the current directory. Since the dirs don't -e in your current directory, they definitely don't -d. Exceptions are . and .., which exist in every directory.

opendir, redir, closedir offer the most power and flexibility; but if you just want to read the files out of directory, you can also glob them:

$path = shift; $path .= "/*" while( $name=glob($path) ) { print "$name"; }

All is well. I learn by answering your questions...

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2024-04-24 08:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found