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


In reply to Re: Reading and executing Perl by ELISHEVA
in thread Reading and executing Perl by bingohighway

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.