我不知道这是否可能,但我想从 Perl 调用一个已知的子类函数。我需要一些“通用”的东西来称呼更具体的东西。我的超类将假定它的子类的所有类都定义了一个已知函数。我想这类似于Java“实现”。
例如,假设我有以下代码:
GenericStory.pm
package Story::GenericStory;
sub new{
my $class = shift;
my $self = {};
bless $self, class;
return $self;
}
sub tellStory {
my $self;
#do common things
print "Once upon a time ". $self->specifics();
}
#
Story1.pm
package Story::Story1;
use base qw ( Story::GenericStory );
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
return $self;
}
sub specifics {
my $self;
print " there was a dragon\n";
}
#
Story2.pm
package Story::Story2;
use base qw ( Story::GenericStory );
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
return $self;
}
sub specifics {
print " there was a house\n";
}
#
MAIN
my $story1 = Story::Story1->new();
my $story2 = Story::Story2->new();
#Once upon a time there was a dragon.
$story1->tellStory();
#Once upon a time there was a house.
$story2->tellStory();
编辑:
代码工作正常。我只是忘记了“我的 $self = shift;” 在tellStory()中;