如何在 Perl 中取消导入函数?

2024-05-07

我正在尝试删除导入的符号,以便它们不能用作对象中的方法,但是no似乎不起作用,也许我不明白不,或者还有其他方法。

use 5.014;
use warnings;
use Test::More;

# still has carp after no carp
package Test0 {
    use Carp qw( carp );
    sub new {
        my $class = shift;
        my $self  = {};

        carp 'good';

        bless $self, $class;
        return $self;
    }
    no Carp;
}

my $t0 = Test0->new;

ok( ! $t0->can('carp'), 'can not carp');

# below passes correctly
package Test1 {
    use Carp qw( carp );
    use namespace::autoclean;

    sub new {
        my $class = shift;
        my $self  = {};

        carp 'good';

        bless $self, $class;
        return $self;
    }
}
my $t1 = Test1->new;
ok( ! $t1->can('carp'), 'can not carp');
done_testing;

不幸的是我不能使用命名空间::自动清洁 https://metacpan.org/module/namespace::autoclean因为我仅限于那些只是核心 Perl 一部分的模块(是的,很愚蠢,但这就是生活)。

而不只是重写namespace::autoclean有没有办法做到这一点?


我相信 namespace::autoclean 会删除 glob:

delete $Test0::{carp};

无需对包进行硬编码:

my $pkg = do { no strict 'refs'; \%{ __PACKAGE__."::" } };
delete $pkg->{carp};

如果你坚持保留严格,你可以愚弄严格(但它或多或少不安全):

my $pkg = \%::;
$pkg = $pkg->{ $_ . '::' } for split /::/, __PACKAGE__;
delete $pkg->{carp};

PS — 为什么来自 StackOverflow 的代码可以接受,而来自 CPAN 的代码不可接受?

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Perl 中取消导入函数? 的相关文章

随机推荐