in reply to Passing file check operators to a function

The following does what you would like, although I'd not recommend this as anything other than a learning exercise. In particular if (-e $filename && -w _) is more efficient than hitting on the file system for each test.

use strict; use warnings; my $filename = "c:\\myfile.txt"; checkit ("-e,-w", $filename) ? print "File $filename exists and is writeable" : print "File $filename does not exist or is not writeable"; sub checkit { my ($tests, $filename) = @_; my @testList = split ",", $tests; for (@testList) { return 0 if ! eval ("$_ '$filename'"); } return 1; }

Note that eval is used to perform the actual test and split is used to generate a list of tests to be performed.


Perl is Huffman encoded by design.

Replies are listed 'Best First'.
Re^2: Passing file check operators to a function
by NetWallah (Canon) on Sep 08, 2005 at 05:10 UTC
    More mods to Grandfather's code to avoid the ugly eval:
    sub checkit { my ($tests, $filename) = @_; my %TestCode=( "-e" => sub{-e $_[0] } , "-w" => sub{-w $_[0] } , "-d" => sub{-d $_[0] } , ); my @testList = split ",", $tests; for (@testList){ exists $TestCode{$_} or return 0; $TestCode{$_}->($filename) or return 0; } return 1; # Passed all tests }
    (Untested)

    Yes, as others have shown, more optimization is possible to avoid multiple stat calls for the same file - the point of THIS post was to avoid the eval.

         "Man cannot live by bread alone...
             He'd better have some goat cheese and wine to go with it!"