[Memphis.pm] AUTOLOAD function
Phil Groce
phil_groce at cmcsmart.com
Tue Mar 21 10:38:49 CST 2000
At 01:35 PM 3/20/00 -0600, Big Ed wrote:
>I knew I was forgetting something for you, Brock. Here's a basic AUTOLOAD
>function:
>
>sub AUTOLOAD {
> my $self = shift;
>
> (my $a = $AUTOLOAD) =~ s/.*:://g;
> @_ ? $self->{$a} = shift
> : return $self->{$a};
> }
>}
Two things to remember about AUTOLOAD:
1. It's not really relevant to this application, but if you don't have a
DESTROY method defined when Perl decides to nuke your object, it calls
AUTOLOAD. If you don't want this, define an empty DESTROY.
2. If you're inheriting from another object, you're probably better off not
using this technique. (Of course, some would say you're better off not
using inheritance. :) For one thing, the child class's AUTOLOAD will be
called before any methods in the parent class, so you'll have to make sure
AUTOLOAD doesn't handle them. So if you want to inherit from an object with
the single public method print(), but you want to auto-get/set everything else:
sub AUTOLOAD {
my $self = shift;
(my $a = $AUTOLOAD) =~ s/.*:://g;
if ($a =~ /print/) {
return $self->SUPER::print;
}
else {
@_ ? $self->{$a} = shift
: return $self->{$a};
}
}
I don't know how this affects a parent class's private methods; probably
badly, since Perl doesn't allow explicit casting -- it'll start looking in
the child object's namespace, regardless.
You also have to protect the parent's data from being corrupted, in about
the same way. (It can also corrupt your data, too, I suppose, but it's less
of danger.) To handle this with any certainty you either have to know
details about the parent's implementation, or it has to explicitly give you
a place to store your instance data.
All that said, this is a pretty neat trick. It breaks for inheritance, but
most of the OO Perl I do uses aggregation to pretty much the same effect.
If you're writing something to get a job (or a prototype) done quickly,
this saves you a lot of time. If you're planning to release something, or
change its implementation to inherit from another object, I'd go with
explicit accessor/mutator methods.
Sorry for the dissertation. :)
phil
----------------------------------------------------------------------------
To unsubscribe, please send email to majordomo at pm.org
with 'unsubscribe memphis-pm-list' in the body of the message.
----------------------------------------------------------------------------
More information about the Memphis-pm
mailing list