in reply to how to pass operators as arguments to a sub

The following test code works fine. Alter it to demonstrate your problem:

use warnings; use strict; checkDir('/usr/tmp', '-w'); #or... checkDir('/usr/tmp', '-r'); sub checkDir { my ($dir, $perm) = @_; print "Dir: $dir, Perm: $perm\n"; }

Prints:

Dir: /usr/tmp, Perm: -w Dir: /usr/tmp, Perm: -r

Bah, read the code!

Ok, better answer - to the actual question:

use warnings; use strict; my $testDir = '.'; checkDir($testDir, '-w'); checkDir($testDir, '-r'); sub checkDir { my ($dir, $perm) = @_; if (eval "$perm '$dir'") { print "Can $perm $dir\n"; } else { print "Can $perm $dir\n"; } }

Prints:

Can -w . Can -r .

This may be a bad idea if the call passes in user supplied text is is not from a trusted place!


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: how to pass operators as arguments to a sub
by kurreburre (Acolyte) on May 03, 2006 at 07:58 UTC
    Thanks, Just what I needed. Completely forgot the eval command. And no, it is not unsafe, the argument comes from my own program, I just wanted to make it general. Cheers Pär