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.
get_started
andset_started
are instance methods (unlikenew
which is a class method), the first argument to them will be an instance of the class, not the class itself. So you should call it$self
or something to avoid confusion. – Portauprince