如何编写在eval块中不触发的SIG {__ DIE__}处理程序? [英] How can I write a SIG{__DIE__} handler that does not trigger in eval blocks?
问题描述
根据 perldoc -f die
$ SIG {__ DIE __}
尽管此功能仅在程序退出前运行,但当前并非如此:
$ SIG {__ DIE __}
钩子即使在逃避的块/字符串中也被调用!如果希望在这种情况下该钩子不执行任何操作,请将die @_ if $ ^ S;
作为处理程序的第一行(请参阅perlvar中的$ ^ S
).因为这会在远处促进奇怪的动作,所以这种反直觉的行为可能会在将来的版本中得到解决.
Although this feature was to be run only right before your program was to exit, this is not currently so: the
$SIG{__DIE__}
hook is currently called even inside evaled blocks/strings! If one wants the hook to do nothing in such situations, putdie @_ if $^S;
as the first line of the handler (see$^S
in perlvar). Because this promotes strange action at a distance, this counterintuitive behavior may be fixed in a future release.
因此,让我们来看一个基本的信号处理程序,该处理程序将通过 eval {die 42}
,
So let's take a basic signal handler which will trigger with eval { die 42 }
,
package Stupid::Insanity {
BEGIN { $SIG{__DIE__} = sub { print STDERR "ERROR"; exit; }; }
}
我们通过以下方式确保这一点
We make this safe with
package Stupid::Insanity {
BEGIN { $SIG{__DIE__} = sub { return if $^S; print STDERR "ERROR"; exit; }; }
}
现在,此操作将不通过 eval {die 42}
触发,但是当相同的代码位于 BEGIN {}
中时将触发像
Now this will NOT trigger with eval { die 42 }
, but it will trigger when that same code is in a BEGIN {}
block like
BEGIN { eval { die 42 } }
这似乎有些晦涩,但它是真实世界,因为您可以看到它被在此方法中使用(其中require
失败,并且被 eval
)捕获,或者在我的情况下,特别是在
This may seem obscure but it's rather real-world as you can see it being used in this method here (where the require
fails and it's caught by an eval
), or in my case specifically here Net::DNS::Parameters
. You may think you can catch the compiler phase too, like this,
BEGIN {
$SIG{__DIE__} = sub {
return if ${^GLOBAL_PHASE} eq 'START' || $^S;
print STDERR "ERROR";
exit;
};
}
哪种方法适用于上述情况,但是不能适用于其中包含BEGIN语句的文档的要求
Which will work for the above case, but alas it will NOT work for a require of a document which has a BEGIN statement in it,
eval "BEGIN { eval { die 42 } }";
总有办法解决此问题并编写一个不会干扰 eval
的 $ SIG {__ DIE __}
处理程序吗?
Is there anyway to solve this problem and write a $SIG{__DIE__}
handler that doesn't interfere with eval
?
推荐答案
检查 caller(1)
使用 [caller(1)]-> [3] eq'(eval)'
return if [caller(1)]->[3] eq '(eval)' || ${^GLOBAL_PHASE} eq 'START' || $^S;
抓取整个调用堆栈
您可以抓取整个堆栈,并确保您不与...进行深入评估,
Crawl entire call stack
You can crawl the entire stack and be sure you're NOT deeply in an eval with,
for ( my $i = 0; my @frame = caller($i); $i++ ) {
return if $frame[3] eq '(eval)'
}
是的,这完全是精神错乱.感谢 irc.freenode.net/#perl
上的mst作为指针.
这篇关于如何编写在eval块中不触发的SIG {__ DIE__}处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!