Where are you going to store your instance data?
Since you asked... in a variable outside the object itself: a
closure, in all likelihood. In my experience, this is the best
use for flyweight objects in Perl, far better than as an awkward
method of strong encapsulation. Here is how I'd do it:
#!/usr/bin/perl
use strict;
use warnings;
package BaseballPlayer;
use Carp;
my %attrib;
sub BEGIN {
%attrib = map { $_ => 1 }
qw( RBI Batting_Average Hits Runs Stolen_Bases Games_Played );
no strict 'refs';
for my $n ( keys %attrib ) { *$n = sub { $_[0]->{$n} } }
}
sub new {
my( $class, %arg ) = @_;
exists $attrib{$_} or croak "Unknown stat: $_" for keys %arg;
$arg{$_} ||= 0 for keys %attrib;
bless \%arg, $class;
}
package BaseballPlayer::Pitcher;
our @ISA = 'BaseballPlayer';
{
my %object;
sub new {
my( $class, %arg ) = @_;
my %pitcher_stat = map { $_ => delete $arg{$_} || 0 } qw( ERA Stri
+keouts );
my $base = BaseballPlayer->new(%arg);
my $ret = bless $base, $class;
$object{$ret} = \%pitcher_stat;
$ret;
}
sub ERA { $object{$_[0]}{ERA} }
sub Strikeouts { $object{$_[0]}{Strikeouts} }
sub DESTROY { delete $object{$_[0]} }
}
package main;
my $p = BaseballPlayer::Pitcher->new( Hits => 23, ERA => 4.32 );
print $p->Hits, "\n";
print $p->ERA, "\n";
Likely you have your own solution; if it is significantly different
(or especially if it's better) than mine, do share it. This solution
passes the tests you mentioned, and has become a regular habit for me.
I agree with your point: Perl doesn't make it easy to use inheritance.
This is a wordy, tiresome ritual, and thus is error-prone. Various
aspects of Perl's OO require such rituals, however; personally, I wouldn't
single out inheritance on this account.
Update: Changed $p's ERA to something realistic, upon zdog's
advice.
Update: Simplified my code, upon tye's advice. My inclusion
of needless code was a cargo-cult imitation of my own practices, which
reflected the needs of prior projects. This, I think, underscores my
point about the unfortunate effects of rituals which compensate for the
shortcomings of a language.
|