在下面的例子中,我有3种不同的语法/机制来定义继承.他们都工作有人可以告诉我哪一个是首选,为什么(是的,我知道“有超过…”).另外,为什么我需要“使用WB”1例而不是其他2. TIA
主要的 –
#!/usr/local/bin/perl -w ####################### use strict; use River; use Ocean; use Lake; my $pName = $0; $pName =~ s/.*\///; $pName =~ s/\.\w+$//; my @sources = (Ocean->new ('Pacific',1),River->new ('Brazos',0),Lake->new ('Tahoe',0) ); foreach (@sources) { $_->printIfSaline ($pName); }
模块(湖,河和海洋继承自WaterBody):
###################### # File: Lake.pm ###################### package Lake; use strict; use WaterBody; our @ISA = ('WaterBody'); sub new { my $class = shift; $class->SUPER::new(@_) } sub printIfSaline { my ($self,$prompt) = @_; my $name = $self->getName(); my $taste = $self->isSaline() ? "salty" : "sweet"; print "$prompt: Lake $name has $taste water\n"; } 1 ###################### # File: Ocean.pm ###################### package Ocean; use strict; use parent 'WaterBody'; sub new { my $class = shift; $class->SUPER::new(@_); } sub printIfSaline { my ($self,$prompt) = @_; my $name = $self->getName; my $taste = $self->SUPER::isSaline() ? "salty" : "sweet"; print "$prompt: $name Ocean has $taste water\n"; } 1 ###################### # File: River.pm ###################### package River; use strict; use base 'WaterBody'; sub new { my $class = shift; $class->SUPER::new(@_); } sub printIfSaline { my ($self,$prompt) = @_; my $name = $self->getName; my $taste = $self->isSaline ? "salty" : "sweet"; print "$prompt: $name river has $taste water\n"; } 1 ###################### # File: WaterBody.pm ###################### package WaterBody; sub new { my $class = shift; my $self = {}; $self->{name} = shift; $self->{saline} = shift; bless $self,$class; return $self; } sub getName { my ($self) = @_; $self->{name} } sub isSaline { my ($self) = @_; $self->{saline} } 1
解决方法
使用父编译指示在编译时设置@ISA.从
parent
Establish an ISA relationship with base classes at compile time
当你使用ParentClass;然后手动设置运行时发生的@ISA.在这种情况下,BEGIN,CHECK或INIT块中的代码将无法使用继承层次结构,无需额外的工作.
使用基本的pragma是较旧的,父级是在docs中推荐的.从base
Unless you are using the fields pragma,consider this module discouraged in favor of the lighter-weight parent
因此,我会用父母说.