legend has asked for the wisdom of the Perl Monks concerning the following question:

I was wondering if the following was possible. I have a condition stored in a string and I want to print out something only if that condition is true. For instance,
$condition = "(($a && $b) || ($c && $d))"; $a = 1; $b = 1; $c = 0; $d = 1; #Now, I have to check the condition. if condition true { print "Your condition is true; print some arbitrary variables here; }
Can someone help me out please?

Replies are listed 'Best First'.
Re: Using a stored condition
by jettero (Monsignor) on Mar 02, 2008 at 21:40 UTC
    You could try any of these:
    my $method1 = '(($a && $b)) || ($c && $d)'; my $method2 = sub { my ($a,$b,$c,$d) = @_; (( $a && $b )) || ($c && $d +) }; }; sub method3 { ... } print "yeah\n" if eval $method1; die $@ if $@; print "yeah\n" if $method2->($a,$b,$c,$d); print "yeah\n" if method3(...);

    -Paul

      Thanks. It says:
      Global symbol "$c" requires explicit package name at script.pl line 41 +. Global symbol "$d" requires explicit package name at script.pl line 41 +. Execution of script.pl aborted due to compilation errors.
      Any idea on what could be wrong?
        I guess it's a line like
        print "yeah\n" if $method2->($a,$b,$c,$d);

        in some scope where $c and $c aren't previously declared. Declare them with my.

        In case you wonder why $a and $b are missing from perl's complaint: Those variables are special. They are used in sort functions, so they exist anyways. It is discouraged to use them for any other purpose. See perlvar.

        --shmem

        _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                      /\_¯/(q    /
        ----------------------------  \__(m.====·.(_("always off the crowd"))."·
        ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
        Because non of variables $a, $b, $c, $d was declared. The question is why $a and $b do not cause problems? The answer: because they are special variables used in sort function. And it is safer not to use them in sample codes because you can get results far from expected.