我想检测我的对象是否是 DESTROY 'd 作为全局破坏的一部分,并打印出警告(因为这显然是一个错误并导致数据丢失)。这样做的明显方法似乎是:
sub DESTROY {
my $self = shift;
# ⋮
if (i_am_in_global_destruction()) {
warn "I survived until global destruction";
}
}
但我一直无法找到检测全局破坏的好方法(而不是正常的引用计数命中 0 破坏)。
通过“好方法”,我的意思不是这个,虽然它适用于 5.10.1 和 5.8.8,但可能会打破第二个有人给它一个奇怪的一瞥:
sub DESTROY {
$in_gd = 0;
{
local $SIG{__WARN__} = sub { $_[0] =~ /during global destruction\.$/ and $in_gd = 1 };
warn "look, a warning";
}
if ($in_gd) {
warn "I survived until global destruction";
}
}'
请您参考如下方法:
有一个模块Devel::GlobalDestruction它使用一点点 XS 让您直接获得全局破坏标志。
更新:自从 perl 5.14.0有一个全局变量${^GLOBAL_PHASE}将设置为 "DESTRUCT"在全局毁灭期间。您通常仍应使用 Devel::GlobalDestruction,因为它可以与 perls 一起使用回到 5.6。使用 ${^GLOBAL_PHASE} 在 perl 上安装时它将使用内置功能,甚至不需要 C 编译器来构建。




