| Next | Tricks of the Wizards | 108 |
In this example, compiling the code repeatedly is a waste of time
Only one variable changes in each accessor
Perl can construct functions that share code without recompiling
sub AUTOLOAD {
# ... as before; set up $method ...
my $code = sub {
my ($self) = @_;
my $val = $self->{$method};
$self->{$method} = shift if @_;
$val;
};
*$AUTOLOAD = $code;
goto &$AUTOLOAD;
}
The new method is a closure
It refers to a private variable, $method
When AUTOLOAD returns, only the new method has a reference to $method
The new methods all share code, but each has its own private $method variable
Method code is compiled only once, along with the rest of your program
| Next | ![]() |
Copyright © 2003 M. J. Dominus |