Re: Using variable to call a Perl built-in function (file tests)

Re: Using variable to call a Perl built-in function (file tests)

am 09.10.2007 09:44:40 von Joe Smith

:-o wrote:
> Whats wrong with code excerpt below?
>
> if ( ("$arg $filename") ne 0) {}

That's not the syntax for calling a function.
You've created a string. You could use eval() on the
string, but it would be better to use a proper code-ref.

> #!/bin/perl -w
> @arg=('-e', '-d', '-r', '-w', '-x', '-S');
> @is=("exists? ", "directory? ", "readable? ", "writeable? ", "executable? ",
> "socket? ");
> @fname=($0, "perl.exe");
> foreach $filename(@fname)
> {
> $ndx=0;
> foreach $argument(@arg)
> {
> print "is $filename a ", $is[$ndx++];
> if ( ("$argument $filename" ) ne 0)
> {
> print "yes\n";
> }
> else
> {
> print "no\n";
> }
> }
> }

The syntax you need is
$result = $reference_to_function->($arguments);



#!/usr/bin/perl
use strict; use warnings;
my %tests = (
'a directory' => sub { -d shift },
'readable' => sub { -r shift },
'writable' => sub { -w shift },
'executable' => sub { -x shift },
'a socket' => sub { -S shift },
'empty' => sub {!-s shift },
);

foreach my $filename ($^X, $0, '/etc', '/etc/hosts', '/dev/null') {
print "$filename\n";
-e $filename or print " does not exist\n" and next;
foreach my $key (sort keys %tests) {
my $is_not = $tests{$key}->($filename) ? '' : 'not ';
print " $is_not$key;";
}
print "\n";
}

############################################################ ##########

/usr/bin/perl.exe
not a directory; not a socket; not empty; executable; readable; not writable;
test-file.pl
not a directory; not a socket; not empty; executable; readable; writable;
/etc
a directory; not a socket; not empty; executable; readable; not writable;
/etc/hosts
not a directory; not a socket; not empty; not executable; readable; not writable;
/dev/null
not a directory; not a socket; empty; not executable; readable; writable;


-Joe

P.S. Newsgroup comp.lang.perl is defunct. Followup-to has been set to
comp.lang.perl.misc, where you should have posted. Also, meaningless
"Subject:" line has been corrected. -Joe