in reply to Reading and executing Perl

In Perl you can compose statements for execution, including if clauses. Just calculate a string with the code you want to execute, and then call it with eval. The only tricky part is making sure that variables get evaluated only when you want them to be evaluated - when building the string or when executing the string. Here's an annotated example:
use strict; use warnings; my $x=45; # \$x prevents $x from being evaluated when we build the # condition. my $sCondition="\$x == 100"; # we're resetting $x now just to prove that # $x will be evaluated later on when we eval the # generated code $x=100; # <<EOF is like "..." but for long multi-line strings # we didn't escape the $ in $sCondition # so $sCondition will be evaluated as part of $sPerl. # MAKE ABSOLUTELY SURE YOU TRUST THE VALUE OF $sCondition # before you use $sPerl. VERY BAD THINGS CAN HAPPEN IF # untrusted strings are used in generated code. # We don't need to declare $x (e.g. my $x) in the generated # code because eval uses variable declarations in the # surrounding code, e.g. the "my $x=45" above my $sPerl = <<EOF; if ($sCondition) { print "Hello, World\n"; } else { print "Goodbye, for now\n"; } 1; EOF # Note: $sPerl ends with 1; so that we are always # guaranteed to exit with a true value unless we # aborted due to an error (in which case eval will # return an undefined (i.e. false) value. # We will use that fact to detect problems in $sPerl # via the code pattern eval(...) or do {...} print "Evaluating:\n$sPerl"; eval($sPerl) or do { warn "Couldn't evaluate <$sPerl>" };

Best, beth