in reply to Reading and executing Perl
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
|
|---|