Runtime evaluation: Difference between revisions

(PHP example (viva la reddit))
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);
Any expression can be passed to [http://perldoc.perl.org/functions/eval.html eval], in run-time the expression is parsed and executed in the same scope as it was called so any variables declared are visible in the <code>eval</code> and variables declared inside the eval still exist afterwards, you can use the <code>return</code> statement to exit the <code>eval</code> returning a value, if omitted, the result of the last expression evaluated will be returned.
$ans = eval( 'abs($a * $b)'); # => 35</lang>
 
<lang perl>($a, $b) = (5, 7);
$ans = eval('abs($a * $b)'); # => 35</lang>
 
=={{header|Python}}==
845

edits