Below is a very ugly hack that I used some time ago, and that has worked until today, for initial (hard-coded) inheritable class data. I'm sure there is a better way of doing this, and I haven't finished my way through Conway's book yet. The initData method manually "walks" through the @ISA hierarchy in a depth-first fashion, incorporating each class' %DATA hash into the object. So you create an object, call its init method (which calls initData), and it populates the object with the appropriate hashes. So in each package you just have to declare the global %DATA hash containing the initial data
Ugly, I know, but it works.
#!/usr/local/bin/perl -w
use strict;
package A;
use vars qw(%DATA);
%DATA=('name' => 'A name',
'data' => 'A data'
);
sub new {
my $class=shift;
my $self={};
bless $self, $class;
}
sub init {
my $self=shift;
my $class=ref($self);
$self->initData($class);
# other initialization here
}
sub initData {
my ($self, $class, $visited)=@_;
$visited={} unless $visited;
# First visit all the superclasses
no strict 'refs';
foreach my $c (@{"${class}::ISA"}) {
$self->initData($c, $visited);
}
# Now take my own %DATA hash
if (!exists($visited->{$class})) {
$self->copyData(%{"${class}::DATA"});
$visited->{$class}=1;
}
}
sub copyData {
my $self=shift;
my %data=@_;
$self->{$_}=$data{$_} foreach keys(%data);
}
####################
package B;
use vars qw(@ISA %DATA);
@ISA=qw(A);
%DATA=('name' => 'B name');
1;
--ZZamboni
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.