【发布时间】: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