我正在研究Perl OO(Perl的新手).我创建了一个简单的示例层次结构:
家长班:
家长班:
#!usr/bin/perl use strict; use warnings; package Objs::Employee; my $started; sub new { my ($class) = @_; my $cur_time = localtime; my $self = { started => $cur_time,}; print "Time: $cur_time \n"; bless $self; } sub get_started { my ($class) = @_; return $class->{started}; } sub set_started { my ($class,$value) = @_; $class->{started} = $value; } 1;
儿童班:
#!/usr/bin/perl package Objs::Manager; use strict; use warnings; use base qw (Objs::Employee); my $full_name; sub new { my ($class,$name) = @_; my $self = $class->SUPER::new(); $self->{full_name} = $name; return $self; } 1;
我尝试按如下方式测试它:
#!/usr/bin/perl use strict; use warnings; use Objs::Manager; my $emp = Objs::Manager->new('John Smith'); use Data::Dumper; print Dumper($emp);
结果:
时间:2013年9月29日星期日12:56:29
$VAR1 = bless( { 'started' => 'Sun Sep 29 12:56:29 2013','full_name' => 'John Smith' },'Objs::Employee' );
问题:为什么转储中的对象报告的是Obj :: Employee而不是Obj :: Manager?
我打电话给经理.
解决方法
总是使用两个参数来祝福,因为$class告诉我们哪个包应该被祝福.如果省略$class,则使用当前包.
bless $self,$class;
产量
$VAR1 = bless( { 'started' => 'Sun Sep 29 13:24:26 2013','full_name' => 'John Smith' },'Objs::Manager' );
来自perldoc -f bless:
Always use the two-argument version if a derived class might inherit the function doing the blessing