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