I am looking into Perl OO (new to Perl). I created a trivial example hierarchy:
Parent class:

#!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;  

Child class:

#!/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;  

I try to test it as follows:

#!/usr/bin/perl  
use strict;  
use warnings;  


use Objs::Manager;  

my $emp = Objs::Manager->new('John Smith');  
use Data::Dumper;  
print Dumper($emp); 

Result:

Time: Sun Sep 29 12:56:29 2013

$VAR1 = bless( {
                 'started' => 'Sun Sep 29 12:56:29 2013',
                 'full_name' => 'John Smith'
               }, 'Objs::Employee' );

Question: Why is the object reported in the dump an Obj::Employee and not an Obj::Manager?
I called new on a Manager.

有帮助吗?

解决方案

Always use two arguments for bless, as $class tells into which package should object be blessed. If $class is omitted, the current package is used.

bless $self, $class; 

output

$VAR1 = bless( {
             'started' => 'Sun Sep 29 13:24:26 2013',
             'full_name' => 'John Smith'
           }, 'Objs::Manager' );

From perldoc -f bless:

Always use the two-argument version if a derived class might inherit the function doing the blessing

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top