I need to eval some code in Perl that might some times contain an exit() call in it. A very simplified example of this would be:
us
You can override exit, but you must do so at compile-time. So use a flag to signal whether the override is active or not.
our $override_exit = 0;
BEGIN {
*CORE::GLOBAL::exit = sub(;$) {
die "EXIT_OVERRIDE\n" if $override_exit;
CORE::exit($_[0] // 0);
};
}
eval {
local $override_exit = 1;
some_function();
};
my $exit_was_called = $@ eq "EXIT_OVERRIDE\n";
die $@ if $@ && !$exit_was_called;
warn("Exit was called\n") if $exit_was_called;
But that creates an exception that might be caught unintentionally. So let's use last instead.
our $override_exit = 0;
BEGIN {
*CORE::GLOBAL::exit = sub(;$) {
no warnings qw( exiting );
last EXIT_OVERRIDE if $override_exit;
CORE::exit($_[0] // 0);
};
}
my $exit_was_called = 1;
EXIT_OVERRIDE: {
local $override_exit = 1;
eval { some_function() };
$exit_was_called = 0;
die $@ if $@;
}
warn("Exit was called\n") if $exit_was_called;
Note that eval BLOCK is used to catch exception. eval EXPR is used to compile code.