Fellow Monks,
Today I encountered some issue trying to use Object inheritance and AUTOLOAD at the same time.
Let me explain : Let's say we have a Dog class, of which a Husky class inherits. AUTOLOAD is used to managed simple attributes, for exampe for setting and getting.
Now there are some attributes that should be managed by AUTOLOAD in the Dog class, and some specific attributes that should be in the Husky class. That raises the problem : AUTOLOAD is only called once, from the package the objects belongs to. There is not AUTOLOAD automatic inheritance.
Easy, will you say, let's call parent AUTOLOAD. Ok, by one must take care of the fact the scalar $AUTOLOAD is only defined in the object package.
So, to make it work, I finally wrote the code below. The idea is really simple, and I guess I may be reinventing the wheel, but anyway... Husky AUTOLOAD is as expected, but finally calls Dog's AUTOLOAD. Dog AUTOLOAD takes care of the fact that it could be called in two ways : either directly, if we have a Dog object, or from Husky AUTOLOAD. Comments are welcome...
# # Parent Object Dog # package Dog; use vars qw/$AUTOLOAD/; sub AUTOLOAD { my ($self, $autoload) = @_; my @attributes = qw / bone /; my $attr = $AUTOLOAD; # If called through Husky, retrieve the original $AUTOLOAD $attr ||= $autoload; $attr =~ s!(.*?)::!!; return unless $attr =~ /[^A-Z]/; # Get rid of DESTROY if ($attr =~ m!get_(.*)! and grep { /^$1$/ } @attributes) { print "Bonga\n"; return $self->{$1}; } } sub new { my $class = shift; return bless {}, $class; } # # Object Husky, A Husky is a Dog ;) # package Husky; #=pod use vars qw/$AUTOLOAD/; sub AUTOLOAD { my $self = shift; my @attributes = qw / eyes /; my $attr = $AUTOLOAD; $attr =~ s!(.*?)::!!; return unless $attr =~ /[^A-Z]/; # Get rid of DESTROY if ($attr =~ m!get_(.*)! and grep { /^$1$/ } @attributes) { print "Bongo\n"; return $self->{$1}; } $self->SUPER::AUTOLOAD($AUTOLOAD); } #=cut use base 'Dog'; # # Main package # package Main; my $billou = new Husky; print "Get bone : \n"; $billou->get_bone; print "Get eyes : \n"; $billou->get_eyes;
--
zejames