【问题标题】:Perl: modules colliding when both import the same modulePerl:当两个导入相同的模块时模块发生冲突
【发布时间】:2012-01-20 14:57:58
【问题描述】:

假设我有两个模块,A 和 Bee,每个模块都使用第三个模块 Shared。

答:

package A;
BEGIN {
    use Shared;
    use Bee;
}

sub new {
    my ($class) = @_;
    my $self = {};
    bless $self, $class;
    $self->B(Bee->new);
    $self;
}

sub B {
    my($self, $B) = @_;
    $self->{b} = $B if defined $B;
    $self->{b};
}

sub test {
    shared_sub();
}

蜜蜂:

package Bee;

BEGIN {
    use Shared;
}

sub new {
    my ($class) = @_;
    my $self = {};
    bless $self, $class;
    $self;
}

sub test {
    shared_sub();
}

1;

共享(注意它没有声明包名):

#!/usr/bin/perl
use strict;
use warnings;
BEGIN {
    require Exporter;

    our @ISA = qw(Exporter);
    our @EXPORT_OK = qw(shared_sub);
}

sub shared_sub {
    print "This is the shared sub in package '" . __PACKAGE__ . "'\n";
}

1;

来自调用 A 的脚本:

use A;
my $A = A->new;
$A->test;       # This is the shared sub in package 'A'
$A->B->test;    # Undefined subroutine &Bee::shared_sub called at Bee.pm line 19.

来自仅调用 Bee 的脚本:

use Bee;
my $B = Bee->new;
$B->test;   # This is the shared sub in package 'Bee'

单独来说,A 和 Bee 都可以毫无错误地调用 test() 方法,但是当我将 Bee 嵌套在 A 中时,突然间,Bee 找不到 Shared 方法了;它不是导入到任何模块调用它的名称空间中吗?

显而易见的答案是给 Shared 自己的包名称,然后更新所有使用它的模块,但我想知道是否有一种方法可以通过更简单的解决方案来避免这样做。

【问题讨论】:

    标签: perl module namespaces package


    【解决方案1】:

    仅将require(因此use)与模块(带有package 的文件)一起使用。否则使用do。如果你不这样做,你就会遇到这个问题。

    require 只执行了一次文件,但是每个使用它的模块都需要运行一次。

    模块只执行一次,但您希望每次执行代码都会执行use Shared;

    Bee 找不到 Shared 方法了

    Shared 从来没有任何方法。没有每个都创建这样的命名空间。

    显而易见的答案是给 Shared 自己的包名,然后更新所有使用它的模块,

    除了Shared.pm,您无需更新任何文件。

    【讨论】:

    • ikegami,你能澄清一些事情吗?首先,我假设要使用do,我只需编码do Module.pm,类似于requireing 或useing 一个模块,是吗?其次,您说我需要更改的唯一文件是Shared.pm,但那不是具有do Module.pm 的文件,对吗?除非我记错了……
    • @Lee Wang,因为你不应该切换到do。您应该添加缺少的package
    猜你喜欢
    • 2013-10-05
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    相关资源
    最近更新 更多