Next Tricks of the Wizards 88

Caching Accessor Methods

        sub AUTOLOAD {
          # ... as before; set up $method ...
          my $code = q{
            sub {
              my ($self) = @_;
              my $val = $self->{METHODNAME};
              $self->{METHODNAME} = shift if @_;
              $val;
            }
          };
          $code =~ s/METHODNAME/$method/g;

          *$AUTOLOAD = eval $code;    
          goto &$AUTOLOAD;
        }


Next Copyright © 2003 M. J. Dominus