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

Rather than passing an operator per se, I'd pass a code reference that uses the operator...

checkDir('/usr/tmp', sub { -w shift }); # need write permission. checkDir('/usr/tmp', sub { -r shift }); # need read permission. checkDir('/usr/tmp', sub { my $x = shift; -r $x and -w $x; }); # need +both. checkDir('/usr/tmp', sub { my $x = shift; not $x =~ /\.\./; }); # safe +ty check. sub checkDir { my ($path, $perm) = @_; ### Check if output dir exists if (! defined $path) { LOG ("Output path not defined; using temp instead...", 1); $path = '/var/tmp/'; } if (! -d $path) { die LOG ("$path is not a valid directory...", 0); } if (! $perm->($path)) { die LOG ("Test failed on $path, not able to use it.", 0); } LOG ("Using $path as output directory...", 2); }

Sanity? Oh, yeah, I've got all kinds of sanity. In fact, I've developed whole new kinds of sanity. Why, I've got so much sanity it's driving me crazy.

Replies are listed 'Best First'.
Re^2: how to pass operators as arguments to a sub
by Tanktalus (Canon) on May 03, 2006 at 17:42 UTC

    While I like this idea, a couple of minor comments. First, there's an awful lot of shifting going on. For things like this, the topicaliser, $_, is very useful. So you'd be able to set things up as:

    checkdir('/usr/tmp', sub { -w $_ }); checkdir('/usr/tmp', sub { -r $_ }); checkdir('/usr/tmp', sub { -r $_ and -w $_ });
    At this point, I want to point out my second minor comment. This is what _ is for.
    # now it's: checkdir('/usr/tmp', sub { -r $_ and -w _ }); checkdir('/usr/tmp', sub { !/\.\./ });
    Again, my next minor comment: I'm not sure what this is supposed to be checking. I'm guessing you're looking for a directory named ".." somewhere in there. However, I'm guessing that "/usr/blah..foo" should be permitted? Regexes are powerful, but with power comes great respon... er, complexity ;-) Rather than use a regex, I would actually suggest doing exactly what a human would do: split the path elements up, and then look that none of them are equal to "..". If that's what you really want. (On unix, I claim that this is almost never what you want, due to symlinks.)
    use List::MoreUtils qw/none/; use File::Spec; checkdir('/usr/tmp', sub { none { $_ eq '..' } File::Spec->splitdir($_) });
    With those minor comments, here's the minor change to checkDir:
    sub checkDir { my ($path, $perm) = @_; ### Check if output dir exists if (! defined $path) { LOG ("Output path not defined; using temp instead...", 1); $path = '/var/tmp/'; } if (! -d $path) { die LOG ("$path is not a valid directory...", 0); } if (! do { local $_ = $path; $perm->() }) { die LOG ("Test failed on $path, not able to use it.", 0); } LOG ("Using $path as output directory...", 2); }
    A bit more convoluted internally, but I think a much more perlish exterior.