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

Hi, I tried to run this code, and seems to not work... $IfCondition = '$TestVar1 eq "XB"'; $TestVar1 = "AB"; if ( $IfCondition ) { print "found"; } else { print "not"; }; .. is there really a way I can create a whole expression inside a variable.. and then execute it inside an IF condition statement?

Replies are listed 'Best First'.
Re: condition clause in a variable?
by Corion (Patriarch) on Mar 14, 2011 at 11:32 UTC

    The easy way would be to look at eval. In the long run, the easy way will give you hard to debug problems and security issues.

    The better way is to hand around anonymous subroutines to check your criteria:

    my $ifCondition = sub { $_[0] eq 'XB' }; print $ifCondition->($TestVar1); if ($ifCondition->($TestVar1)) { print "TestVar1 (value '$TestVar1') matches the condition."; };

    Update: jethro spotted a missing sub