eval{
require $file;
}
/*subsequent code goes here*/
...
If $file
contains an exit
statement, the subsequent code 开发者_如何学Cdoesn't have a chance to run.
How to work around so that the subsequent code always get its chance to run when eval
is done??
It's not possible to abort the exit
call. $file
should use die
instead, which can be trapped by an eval
.
As a workaround, you can override the exit
builtin globally:
BEGIN {
*CORE::GLOBAL::exit = sub { die "About to exit" }
}
Have a look at the Safe.pm
module. It allows you to restrict which operators can be executed . It was meant for situations where you need to execute untrusted code.
Haven't done this, but you might be able to redefine perl's exit function with your own that does a die() of a message your main code is aware of. You would then use CORE::exit(), if I remember, to get a true exit.
Better would be to run the new code in a package other than main:: so you don't corrupt main::s exit.
2011-Aug-06 update: for giggles I tried it:
my $code = qq[print qq(hello exit 99\n); exit 99;]; { package Foo; local $@; use vars qw(*exit); #required local *exit = sub { die "TRAPPED EXIT: @_\n"; }; #override local to package Foo; print "doing eval\n"; eval $code; print "reason=$@\n"; } print "done\n"; #prove we did not truly exit exit 2; #set specific exit code
And yes, Safe.pm is nice for untrusted code, but if the code is trusted, this is easier.
perl exit.pl; echo $? doing eval hello exit 99 reason=TRAPPED EXIT: 99 done 2
精彩评论