Perl:模块在导入同一模块时发生冲突

时间:2012-01-20 06:23:33

标签: perl module namespaces package

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

A:

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自己的包名,然后更新所有使用它的模块,但我想知道是否有办法避免使用更简单的解决方案。

1 个答案:

答案 0 :(得分:4)

仅对模块(具有require的文件)使用use(以及package)。否则请使用do。如果你不这样做,你会遇到这个问题。

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

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

Bee无法再找到Shared方法

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

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

您不必更新Shared.pm以外的任何文件。