Runtime evaluation: Difference between revisions
→{{header|Perl}}: Rewrote.
(PHP example (viva la reddit)) |
Underscore (talk | contribs) (→{{header|Perl}}: Rewrote.) |
||
Line 237:
=={{header|Perl}}==
The <code>eval</code> function accepts a block or a string as its argument. The difference is that a block is parsed at compile-time, whereas a string is parsed at runtime. The block or string may represent any valid Perl program, including a single expression. The subprogram executes in the same lexical and dynamic scope as the surrounding code. The return value of a call to <code>eval</code> depends on how the subprogram terminates:
* If control reaches the end of the subprogram, <code>eval</code> returns the value of the last expression evaluated.
* If the subprogram uses an explicit <code>return</code>, <code>eval</code> returns the given value.
* If the subprogram throws an exception, <code>eval</code> returns <code>undef</code>. The text of the exception is assigned to <code>$@</code>. (When the subprogram terminates without an exception, <code>$@</code> is set to the null string instead.)
<lang perl>my ($a, $b) = (-5, 7);▼
▲<lang perl>($a, $b) = (5, 7);
▲$ans = eval('abs($a * $b)'); # => 35</lang>
=={{header|Python}}==
|