in reply to File testing via list of test operators

You can get rid of eval (potential security risk) and even define some new tests like so:

use strict; use warnings; my %tests = ( # key, description, anonymous test function -s => { dsc => "size > 0", ftest => sub { -s $_[0] } }, -T => { dsc => "type Text", ftest => sub { -T $_[0] } }, -B => { dsc => "is Binary", ftest => sub { -B $_[0] } }, -r => { dsc => "is readable", ftest => sub { -r $_[0] } }, -z => { dsc => "is Zero bytes", ftest => sub { -z $_[0] } }, lt100 => { dsc => "small file", ftest => sub { -s $_[0] < 100 } + }, ); my $myfile = $0; print "Tests for '$myfile':\n"; foreach my $t (keys %tests) { my $result = $tests{$t}{ftest}->( $myfile ) || 0; print $result ? 'Passed' : 'Failed'; print " [$t]\t test ($tests{$t}{dsc})\t with result ($result)\n"; } __END__ Tests for 'ftest.pl': Passed [-r] test (is readable) with result (1) Passed [-T] test (type Text) with result (1) Failed [lt100] test (small file) with result (0) Failed [-z] test (is Zero bytes) with result (0) Failed [-B] test (is Binary) with result (0) Passed [-s] test (size > 0) with result (780)
sub { -s $_[0] } is a little shorter than  sub { my $filename = shift; return -s $filename; } which is more comprehensible.

Replies are listed 'Best First'.
Re^2: File testing via list of test operators
by robh (Initiate) on Dec 21, 2010 at 15:14 UTC
    Great answers everyone. Thanks very much. I love the final solution provided Perlbotics. Awesome. Thanks!