in reply to Re: Generally accepted style in Perl objects
in thread Generally accepted style in Perl objects
That will auto-create "set" and "get" methods and install them in the symbol table for you. Subsequent calls to those methods will find them and not incur the AUTOLOAD overhead. Needless to say, this method is useful primarily if you have many subs with similar functionality.sub AUTOLOAD { no strict 'refs'; my ($self, $newval) = @_; # was it a get_... method? if ( $AUTOLOAD =~ /.*::get(_\w+)/ ) { my $attr_name = $1; *{ AUTOLOAD } = sub { return $_[ 0 ]->{ $attr_name } }; return $self->{ $attr_name }; } # was it a set_... method? if ( $AUTOLOAD =~ /.*::set(_\w+)/ ) { my $attr_name = $1; *{ AUTOLOAD } = sub { $_[ 0 ]->{ $attr_name } = $_[ 1 ]; retur +n } }; $self->{ $attr_name } = $newval; return; } # Whups! Bad sub croak "No such method: $AUTOLOAD"; }
Incidentally, the "simplification" I mentioned was my removal of a hash lookup to verify whether or not one was allowed to read or update the variable in question. You'll want to account for that. I left it out so the code would be clearer.
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
|
|---|