这是一个有趣的 Perl 行为。(至少对我来说:))
我有两个包PACKAGE1
,PACKAGE2
它们导出具有相同名称的函数Method1()
。
由于将有很多包会导出相同的功能,所以use
在 Perl 文件中添加所有内容将是乏味的。所以,我创建了一个包含INCLUDES.pm
这些文件的通用包含文件use
。
包括.pm:
use PACKAGE1;
use PACKAGE2;
1;
包装1.pm:
package PACKAGE1;
use Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw (
Method1
);
sub Method1{
print "PACKAGE1_Method1 \n";
}
1;
包2.pm:
package PACKAGE2;
use Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw (
Method1
);
sub Method1{
print "PACKAGE2_Method1 \n";
}
1;
测试.pl:
##################first package################
package Test1;
use INCLUDES;
my @array = values(%INC);
print "@array \n";
Method1();
##################second package################
package Test2;
use INCLUDES; #do "INCLUDES.pm";
my @array = values(%INC);
print "@array \n";
Method1();
Method1()
动机是,在任何 Perl 文件中只能使用最新的包。
输出让我吃惊。我希望这两个Method1()
电话都Tests.pl
应该成功。但只有第一个Method1()
执行,第二个Method1()
调用说“未定义”。
输出:
C:/Perl/site/lib/sitecustomize.pl PACKAGE1.pm C:/Perl/lib/Exporter.pm PACKAGE2
.pmINCLUDES.pm
PACKAGE2_Method1
C:/Perl/site/lib/sitecustomize.pl PACKAGE1.pm C:/Perl/lib/Exporter.pm PACKAGE2
.pm INCLUDES.pm
Undefined subroutine &Test2::Method1 called at C:\Temp\PackageSample\Tests.pl line 15.
有人对此有任何答案/看法吗?
实际场景:
多个 Perl 模块中的方法将具有相同的名称。但是只能使用高优先级 perl 模块中的方法。
例如,如果PACKAGE1
contains Method1(), Method2()
& PACKAGE2
contains only Method1()
,Method1()
则应使用 from PACKAGE2
&Method2()
应使用 fromPACKAGE1
基本上我想在基于 Preference 的模块之间实现层次结构。有什么办法吗?