in reply to Pass conditions to a subroutine

You could use eval EXPR, but passing a sub reference is safer, clearer and easier.

my $condition = sub { !-d $_[0] }; my $result = checkForDirectory($condition); sub checkForDirectory { my $condition = shift; ... if ($condition->($someDir)) { doSomethingElse(); } }

Replies are listed 'Best First'.
Re^2: Pass conditions to a subroutine
by Fletch (Bishop) on May 13, 2008 at 19:15 UTC

    Of course you could take advantage of one of the few times you would actually want to use a prototype and allow a more streamlined syntax:

    sub checkForDirectory (&) { my $cond = shift; ## ... } ## ... my $result = checkForDirectory { ! -d $_[0] }; my $also_result = checkForDirectory sub { -M $_[0] > 2 }

    Although doing it this way means that if your coderefs aren't inline (say they're coming from an array or hash based on some other external condition) you'll need to use a leading & to override the prototype check . . .

    my $predicate = sub { $_[0] =~ /^\d{4}-\d{2}-\d{2}/ }; my $other_result = &checkForDirectory( $predicate );

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re^2: Pass conditions to a subroutine
by PerlRob (Sexton) on May 13, 2008 at 18:08 UTC
    Thanks to all--exactly what I was looking for!