Jam*_*ren 2 perl inheritance object
我有以下内容.
package A;
sub new {
my ($class) = @_;
my $self = { };
bless $self, $class;
return($self);
}
sub run() {
die "Task: ",__PACKAGE__, "requires a run method";
}
package B;
use A;
our @ISA = qw(A);
sub new {
my ($class) = @_;
my $self = { };
bless $self, $class;
return($self);
}
package C;
use A;
my @Tasks;
sub new {
my ($class) = @_;
my $self = { };
bless $self, $class;
return($self);
}
sub add{
my($self,$tempTask) = @_ ;
push(@Tasks,$tempTask);
$arraysize = @Tasks;
}
sub execute{
foreach my $obj (@Tasks)
{
$obj->run();
}
}
1;
Run Code Online (Sandbox Code Playgroud)
脚本
#!/usr/local/bin/perl
use strict;
use C;
use B;
my $tb = new C();
my $task = new B();
$tb->add($task);
$tb->execute();
Run Code Online (Sandbox Code Playgroud)
包B没有run方法,所以它默认为Package A run方法,这就是我想要的.在这一点上,我希望它打印出包B的名称(将继承包A的许多不同的包,但它没有.
目前,它使用__PACKAGE__变量打印出包A.
有帮助吗?
Axe*_*man 10
对象是受祝福的引用.__PACKAGE__将始终等于当前包的名称.但是ref( $object )会给你对象类的名称.还有Scalar::Util::blessed,对于非祝福的参考文献,它不会给你误报.
use Scalar::Util qw<blessed>;
my $obj = bless {}, 'A';
my $class = ref( {} ); # HASH
$class = blessed( {} ); # ''
$class = ref( $obj ); # A
$class = blessed( $obj ); # A
Run Code Online (Sandbox Code Playgroud)
所以在你的特殊情况下:
sub run() {
die "Task: " . ref( shift ) . "requires a run method";
}
Run Code Online (Sandbox Code Playgroud)