在 Perl 中检测全局破坏 [英] Detecting global destruction in Perl

查看:42
本文介绍了在 Perl 中检测全局破坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检测我的对象是否被DESTROY作为全局破坏的一部分,并打印出警告(因为这显然是一个错误并导致数据丢失).这样做的明显方法似乎是:

I'd like to detect if my object is being DESTROY'd as part of global destruction, and print out a warning (as that'd clearly be an error and lead to data loss). The obvious way to do that would seem to be:

sub DESTROY {
    my $self = shift;
    # ⋮
    if (i_am_in_global_destruction()) {
        warn "I survived until global destruction";
    }
}

但我一直无法找到检测全局破坏的好方法(而不是正常的 refcount hit 0 破坏).

but I have been unable to find a good way to detect global destruction (instead of normal refcount hit 0 destruction).

通过好方法",我的意思不是这个,虽然它适用于 5.10.1 和 5.8.8,但可能会打破第二个有人给它一个奇怪的眼神:

By "good way", I mean not this, which though it works on 5.10.1 and 5.8.8, probably breaks the second someone gives it an odd glance:

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 让你直接获取全局销毁标志.

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

更新:自从 perl 5.14.0 有一个全球变量 ${^GLOBAL_PHASE} 将在全局销毁期间设置为 "DESSTRUCT".您通常仍然应该使用 Devel::GlobalDestruction,因为它可以与 5.6 的 perls 一起使用.当使用 ${^GLOBAL_PHASE} 在 perl 上安装时,它将使用内置功能,甚至不需要 C 编译器来构建.

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.

这篇关于在 Perl 中检测全局破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆