6

我想检测我的对象是否被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";
    }
}'
4

2 回答 2

11

There's a module Devel::GlobalDestruction that uses a tiny bit of XS to let you get at the global destruction flag directly.

Update: since perl 5.14.0 there is a global variable ${^GLOBAL_PHASE} that will be set to "DESTRUCT" during global destruction. You should still generally use Devel::GlobalDestruction, since it works with perls back to 5.6. When installing on a perl with ${^GLOBAL_PHASE} it will use the built-in feature and not even require a C compiler to build.

于 2011-02-04T20:48:15.507 回答
8

一个对我来说足够好的解决方案是在一个END块中设置一个标志。

package Whatever;
our $_IN_GLOBAL_DESTRUCTION = 0;
END {
    $_IN_GLOBAL_DESTRUCTION = 1;
}
于 2011-02-04T21:04:20.270 回答