sub new() {
my $class = shift; # get class so constructor can be inherited
my $self = {};
bless ($self,$class);
$self->_init( @_ ); # call _init here or in subclass
return $self;
}
sub _init {
my $self = shift;
$self->{NAME} = shift || undef;
$self->{AGE} = undef;
$self->{COLOR} = undef;
$self->awaken;
}
sub awaken {
my $self = shift;
($self->get_name eq "nameless") ? print "A " : 0;
print $self->get_name .", ";
($self->get_name ne "nameless") ? print "an " : 0;
print $self->get_age .", ";
print $self->get_color ." dragon awakens from his slumber!\n";
}
####
sub _init {
my $self = shift;
if ($self->SUPER::_init( @_ )) {
$self->{NAME} = "Trogdor";
$self->{AGE} = "one year old";
$self->{COLOR}= "green";
$self->burninate;
}
print "Trogdor::_init got called\n";
}
####
package Dragon;
use strict;
sub new() {
my $class = shift; # get class so constructor can be inherited
my $self = {};
bless ($self,$class);
$self->_init( @_ ); # call _init here or in subclass
return $self;
}
sub _init {
my $self = shift;
$self->{NAME} = shift || undef;
$self->{AGE} = undef;
$self->{COLOR} = undef;
$self->awaken;
}
sub get_name {
my $self = shift;
return $self->{NAME} || "nameless";
}
sub get_age {
my $self = shift;
return $self->{AGE} || "ageless";
}
sub get_color {
my $self = shift;
return $self->{COLOR} || "obscure";
}
sub awaken {
my $self = shift;
($self->get_name eq "nameless") ? print "A " : 0;
print $self->get_name .", ";
($self->get_name ne "nameless") ? print "an " : 0;
print $self->get_age .", ";
print $self->get_color ." dragon awakens from his slumber!\n";
}
1;
####
package Trogdor;
use strict;
use base qw(Dragon);
sub _init {
my $self = shift;
if ($self->SUPER::_init( @_ )) {
$self->{NAME} = "Trogdor";
$self->{AGE} = "one year old";
$self->{COLOR}= "green";
$self->burninate;
}
print "Trogdor::_init got called\n";
}
sub awaken {
my $self = shift;
($self->get_name eq "nameless") ? print "A " : 0;
print $self->get_name .", ";
($self->get_name ne "nameless") ? print "an " : 0;
print $self->get_age .", ";
print $self->get_color ." dragon awakens from his slumber!(from Trogdor)\n";
}
sub burninate {
my $self = shift;
return $self->get_name ." burninates the land!\n";
}
1;
####
#!/usr/bin/perl
use strict;
use Trogdor;
#my $d = new Dragon(); # create a nameless dragon
#my $d = new Dragon("Smaug"); # create a dragon named Smaug
my $d = new Trogdor(); # create Trogdor
print $d->get_color; # confirm Trogdor's color is reset
####
Using perl 5.8.1-RC3 unless otherwise noted.
Apache/1.3.33 (Darwin) unless otherwise noted.
Mac OS X 10.3.9 unless otherwise noted.