http://qs321.pair.com?node_id=477619


in reply to Stopping execution of an eval statement

While this isn't what you asked, your evaluate() routine only works in this case by accident of positioning. When it eval's your code, it can only see the lexical $x because the evaluate() subroutine happens to be in the same scope as the original declaration. If you moved the evaluate() subroutine above $x's declaration or out of scope entirely (say, into a library file) things break.

#!/usr/bin/perl -w use strict; sub evaluate{ my $perl=shift || return; print "evaluate\n$perl\n\n"; my $rtn=eval($perl); if($@){return $@;} return $rtn; } my $x=42; my $evalstatement=q| $x; |; print evaluate($evalstatement);
evaluate $x; Global symbol "$x" requires explicit package name at (eval 1) line 2.

For lexical purposes the code is executed at the point eval() is run, not where evaluate() is called. You can't safely use lexicals in code eval'd somewhere else which means you can't safely have a subroutine which takes any ol code as an argument and eval's it.

Also your eval code would be a lot simpler with q{}.