in reply to A Tribute To The Monks Of Wisdom

To amplify a bit on what hossman said, it's better to use the so-called "-X" operators on file names, before you open the files, because you usually want to know if they exist, are writable, etc, before trying to open them. Of course, if the path/filename doesn't exist, there's no point trying to get more information about it.

And it's also worthwhile to know that every time you use any one of the -X operators on a given file, it fetches all the properties for the file (because that's how the underlying system library function works), and it keeps them in a cache, so if you use another -X function on the same file as the previous -X function, you can use "_" (underscore) instead of the file name or file handle, to use the cached info instead of reading it from disk again.

Plus, I like having things structured for loops, and I hate having to repeat things in my perl code when I shouldn't need to... even if it means using "eval" so that I can loop over the tests:

#!/usr/bin/perl use strict; use warnings; my %test = ( '-f' => 'a data file', '-d' => 'a directory', '-r' => 'readable', '-w' => 'writable', '-x' => 'executable', ); die "Usage: $0 [path/]file.name ...\n" unless @ARGV; for my $file ( @ARGV ) { my $report = "$file does not exist\n"; if ( -e $file ) { $report = "$file exists and is:\n"; for my $t ( sort keys %test ) { $report .= " ... $test{$t}\n" if ( eval "$t _" ); } } print "$report\n"; }

Replies are listed 'Best First'.
Re^2: A Tribute To The Monks Of Wisdom
by NetWallah (Canon) on Nov 16, 2008 at 20:01 UTC
    Liked your code (++), but wanted to avoid "eval" - this works :
    #!/usr/bin/perl use strict; use warnings; my %test2 = ( 'a data file' => sub {-f _}, 'a directory' => sub {-d _}, 'readable' => sub {-r _}, 'writable' => sub {-w _}, 'executable' => sub {-x _}, ); die "Usage: $0 [path/]file.name ...\n" unless @ARGV; for my $file ( @ARGV ) { my $report = "$file does not exist\n"; if ( -e $file ) { $report = "$file exists and is:\n"; for my $t ( sort keys %test2 ) { $report .= " ... $t\n" if $test2{$t}->(); } } print "$report\n"; }

         Have you been high today? I see the nuns are gay! My brother yelled to me...I love you inside Ed - Benny Lava, by Buffalax