DekGenius.com
[ Team LiB ] Previous Section Next Section

A.9 Answer for Chapter 10

A.9.1 Exercise (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);
}
}
    [ Team LiB ] Previous Section Next Section