[Mpls-pm] Dumb Question...Module Method - Dual Name

Dave Rolsky autarch at urth.org
Tue Oct 25 20:14:09 PDT 2005


On Tue, 25 Oct 2005, Joshua ben Jore wrote:

> You were doing so well that I didn't want to interrupt. I'd like to
> make one small note here. If you're tempted to install methods from
> within AUTOLOAD, be aware that you're invalidating perl's method
> cache. On perlmonks.org, suggestions to use AUTOLOAD are often
> followed by clever suggestions to have AUTOLOAD remove itself by
> installing the looked-up function into the symbol table. This is fine
> except that it causes the global method cache to get invalidated.

AUTOLOAD also breaks calls to ->can(), unless you overload that as well.

Frankly, I think AUTOLOAD is bad, bad, bad, and I question it's use at 
all.

It's often possible to get the same effect by generating subs at compile 
time:

   for my $meth ( qw( foo bar ) )
   {
       my $sub = sub { $_[0]->{$meth} };
       no strict 'refs';
       *{$meth} = $sub;
   }

Now you have a nice efficient closure implementing those accessors and 
->can() works like it should, as does Perl's method cache.  There are, of 
course, various modules on CPAN to do this sort of method generation for 
you, such as Class::MethodMaker.


-dave

/*===================================================
VegGuide.Org                        www.BookIRead.com
Your guide to all that's veg.       My book blog
===================================================*/


More information about the Mpls-pm mailing list