我有这两个模块:
package G1;
sub new {
my $class = shift;
my $self = {
one => 1,
two => 2,
three => 3
};
bless $self,$class;
return $self;
}
sub three {
my $self = shift;
print "G1 green is ",$self->{three};
}
1;
package G2;
our @ISA = qw(G1);
#use base qw(G1);
sub new {
my $class = shift;
my $self = $class->SUPER::new();
$self->{three} = 90;
bless $self,$class;
return $self;
}
sub three {
my $self = shift;
print "G2 rox!\n";
$self->SUPER::three();
}
1;
以及以下脚本:
use G2;
my $ob = G2->new();
$ob->three();
运行脚本时,会产生以下错误:
Can't locate object method "new" via package "G2" at G2.pm line 8.
如果我将@ISA
行替换为use base
,则脚本可以正常运行。我试图覆盖一些方法并在之后调用原始方法。我做错了什么?
答案 0 :(得分:4)
因为G2.pm需要包含use G1;
行。没有它,G1.pm
永远不会被加载。如果你运行警告,Perl会告诉你:
$ perl -w t.pl
Can't locate package G1 for @G2::ISA at t.pl line 1.
Can't locate package G1 for @G2::SUPER::ISA at G2.pm line 8.
Can't locate package G1 for @G2::SUPER::ISA at G2.pm line 8.
Can't locate object method "new" via package "G2" at G2.pm line 8.
注意所有无法找到包G1 ... 错误。
要明确,use base 'G1'
有效,因为它也有use G1
。
答案 1 :(得分:2)
G2需要了解G1,而不仅仅是名字。添加
require G1;
到G2.pm。