## Additional Instance Variables in Subclasses
{ package Animal;
sub named {
my $class = shift;
my $name = shift;
bless \$name, $class;
}
sub name {
my $either = shift;
ref $either
? $$either : "an unamed $either"; # see above section for usage
}
sub speak {
my $either = shift;
print $either->name," goes ",$either->sound,"!\n";
}
sub eat {
my $either = shift;
my $food = shift;
print $either->name," eats $food.\n";
}
sub DESTROY {
my $self = shift;
print "[",$self->name," has died.]\n";
}
}
{ package Horse;
our @ISA = qw/Animal/;
sub sound { "neigh"; }
sub DESTROY {
my $self = shift;
$self->SUPER::DESTROY;
print "[",$self->name," has gone off to the glue factory.]\n";
}
}
{ package Sheep;
our @ISA = qw/Animal/;
sub sound { "baaah"; }
}
{ package Cow;
our @ISA = qw/Animal/;
}
sub feed_a_cow_named {
my $name = shift;
my $cow = Cow->named($name);
$cow->eat("grass");
print "Returning from the subroutine.\n"; # $cow is destroyed here
}
{ package Barn;
sub new { bless [], shift }
sub add { push @{+shift}, shift }
sub contents { @{+shift} }
sub DESTROY {
my $self = shift;
print "$self is being destroyed...\n";
for($self->contents) {
print " ",$_->name," goes homeless.\n";
}
}
}
{ package Barn2;
sub new { bless [], shift }
sub add { push @{+shift}, shift }
sub contents { @{+shift} }
sub DESTROY {
my $self = shift;
print "$self is being destroyed...\n";
while(@$self) {
my $homeless = shift(@$self);
print " ",$homeless->name," goes homeless.\n";
}
}
}
{ package RaceHorse;
our @ISA = qw/Horse/;
## extend PARENT constructor
sub named {
my $self = shift->SUPER::named(@_);
print "DEBUG: $self\n\n";
$self->{$_} = 0 for qw/wins places shows losses/;
$self;
}
sub won { shift->{wins}++; }
sub placed { shift->{places}++; }
sub showed { shift->{shows}++; }
sub lost { shift->{losses}++; }
sub standings {
my $self = shift;
join ", ", map "$self->{$_} $_", qw/wins places shows losses/;
}
}
my $racer = RaceHorse->named("Billy Boy");
# record the outcomes: 3 wins, 1 show, 1 loss
$racer->won;
$racer->won;
$racer->won;
$racer->showed;
$racer->lost;
print $racer->name," has standings of: ",$racer->standings,".\n";
####
Not a HASH reference at notes_chap_10.perl line 303.
####
$self->{$_} = 0 for qw/wins places shows losses/;