For instance, you could use AUTOLOAD to be lazy about providing object accessors. But I prefer this more explicit way:
I got that idea from this post a while back. In my opinion, it's just a better way of "lazily" providing accessors than with AUTOLOAD. Although it's a little more typing, it's still much less typing that writing out every sub by hand, and it better expresses my intent. (i.e, I don't want to waste time filtering out every misspelled method call)## only generate explicitly listed subs: BEGIN { no strict 'refs'; my @fields = qw/ name age favorite_color ... /; for my $f (@fields) { *$f = sub { ## argument, error checking, etc return $_[0]->{$f}; }; } } ## instead of sub AUTOLOAD { (my $func = $AUTOLOAD) =~ s/.*::/; ## argument, error checking, etc.. ## is $func a valid method?? return $_[0]->{$func}; }
Sometimes this isn't feasible -- sometimes it doesn't make sense to try anticipating every possibility. Other times you must cover different sets of method names depending on various contexts (i.e., you must look at the passed data and $AUTOLOAD before you know if it's a valid request). For instance, a while back I wrote a bare-bones object-persistence class à la Class::DBI. Because it was a superclass for many other object classes, I had to use AUTOLOAD for the accessors/mutators, because a name method might be ok for one subclass, but not another. This is where the power of AUTOLOAD really shines.
blokhead
In reply to Re: is autoload bad style?
by blokhead
in thread is autoload bad style?
by racer_x
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |