in reply to Re: oo design q: SUPER::_init
in thread oo design q: SUPER::_init

Thanks to both of you for your help. Incidentally, lestrrat, there is a minor error in your (elegant) solution: my %args = @_; assigns to the hash keys, so the foreach loop $self->{key} = $args{$key} actually assigns a null value to $self->{key}.

I mention this just in case someone else grabs this code in the future and spends a few minutes scratching their head, like I did. Luckily, the fix is even simpler:

package Dragon sub _init { my $self = shift; foreach my $key qw(NAME AGE COLOR) { $self->{$key} = shift; } }

In the unlikely event that anyone is interested, my complete code follows:

Dragon.pm
package Dragon; use strict; sub new() { my $class = shift; # get class so constructor can be inhe +rited my $self = {}; bless ($self,$class); $self->_init( @_ ); # call _init here or in subclass $self->awaken; # arise from your slumber! return $self; } sub _init { my $self = shift; foreach my $key qw(NAME AGE COLOR) { $self->{$key} = shift; } } sub get_name { my $self = shift; return $self->{NAME} || "nameless"; } sub get_age { my $self = shift; return $self->{AGE} || "ageless"; } sub get_color { my $self = shift; return $self->{COLOR} || "obscure"; } sub awaken { my $self = shift; ($self->get_name eq "nameless") ? print "A " : 0; print $self->get_name .", "; ($self->get_name ne "nameless") ? print "an " : 0; print $self->get_age .", "; print $self->get_color ." dragon awakens from his slumber!\n"; } 1;
Trogdor.pm
package Trogdor; use strict; use base qw(Dragon); sub _init { my $self = shift; $self->{NAME} = "Trogdor"; $self->{AGE} = "one year old"; $self->{COLOR}= "green"; } sub burninate { my $self = shift; print $self->get_name ." burninates the land!\n"; } 1;
dragons.pl
#!/usr/bin/perl use strict; use Dragon; use Trogdor; my $d = new Dragon(); # create a nameless dragon my $smaug = new Dragon("Smaug","centuries old"); # create Smaug my $trogdor = new Trogdor(); # create Trodgor $trogdor->burninate(); # burninate!

AH

----------
Using perl 5.8.1-RC3 unless otherwise noted. Apache/1.3.33 (Darwin) unless otherwise noted. Mac OS X 10.3.9 unless otherwise noted.