Next Tricks of the Wizards 105

Direct Emulation of Accessors

        my @attrs = qw(color size price ... );  # 637 of these
        my %is_attr = map {$_ => 1} @attrs;
        ...
        sub AUTOLOAD {
          my $self = shift;
          my ($package, $method) = ($AUTOLOAD =~ /(.*)::(.*)/);
          unless ($is_attr{$method}) {
            croak "No such attribute: $method; aborting";
          }
          my $val = $self->{$method};
          $self->{$method} = shift if @_;
          $val;
        }
        $object->color('red');     # set object's color
        $size = $object->size;     # fetch object's size


Next Copyright © 2003 M. J. Dominus