Perl Cd Bookshelf [Electronic resources]

نسخه متنی -صفحه : 875/ 713
نمايش فراداده

A.9. Answer for Chapter 10<a class="libraryIndexlink" href="index.aspx?pid=31159&BookID=23871&PageIndex=296&Language=3#lrnperlorm-CHP-10-SECT-7.1">Section 10.7.1</a>)

A.9. Answer for Chapter 10

Section 10.7.1)

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 zeroes 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);
}
}