in reply to Re: Generally accepted style in Perl objects
in thread Generally accepted style in Perl objects

One thing to consider: while you can use AUTOLOAD to create those methods for you, it has a lot of overhead. If those methods are to be called frequently, you can write them by hand *or* use AUTOLOAD and have it install the methods directly to the symbol table. Here's a (simplified) routine from Object-Oriented Perl by Damian Conway:
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"; }
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.

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.