Section A.12. Answer for Chapter 13


A.12. Answer for Chapter 13

A.12.1. Exercise

First, start the class:

 { package RaceHorse;   our @ISA = qw(Horse); 

Next, use a simple dbmopen to associate %STANDINGS with permanent storage:

 dbmopen (our %STANDINGS, "standings", 0666)   or die "Cannot access standings dbm: $!"; 

When a new RaceHorse is named, either pull the existing standings from the database or invent zeros for everything:

 sub named { # class method   my $self = shift->SUPER::named(@_);   my $name = $self->name;   my @standings = split ' ', $STANDINGS{$name} || "0 0 0 0";   @$self{qw(wins places shows losses)} = @standings;   $self; } 

When the RaceHorse is destroyed, the standings are updated:

 sub DESTROY { # instance method, automatically invoked   my $self = shift;   $STANDINGS{$self->name} = "@$self{qw(wins places shows losses)}";   $self->SUPER::DESTROY; } 

Finally, the instance methods are defined:

 ## instance methods: 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); } 




Intermediate Perl
Intermediate Perl
ISBN: 0596102062
EAN: 2147483647
Year: N/A
Pages: 238

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net