[Biodevelopers] Object Oriented Perl issue
Steve O
bub at io.com
Wed Apr 24 17:25:14 EDT 2002
Joe,
You might want to check out Damian Conway's book Object Oriented Perl.
He shows how to use perl's AUTOLOAD feature to create get/set
methods on the fly if they don't exist. This allows you to write
get/set methods that have interesting behavior, and leave the simple
ones for perl to make up.
Here's the example:
sub AUTOLOAD {
my ( $self, $newval ) = @_;
if ($AUTOLOAD =~ /.*::get(_\w+)/ && $self->_accessable( $1, 'read' ))
{
my $attr_name=$1;
*{$AUTOLOAD} = sub { return $_[0]->{$attr_name} };
return $self->{$attr_name};
}
elsif ($AUTOLOAD =~ /.*::set(_\w+)/ && $self->_accessable( $1, 'write'))
{
my $attr_name=$1;
*{$AUTOLOAD} = sub { $_[0]->{$attr_name} = $_[1]; return };
return $self->{$attr_name} = $newval;
}
croak "No such method: $AUTOLOAD";
}
The argument I think OO people would have with your get_attribute
and set_attribute functions is that it allows access to all
of the object's state and allows no extra processing. The methods
are providing no extra benefit over the simpler:
$object->{fragment}="foo";
print "fragment: ",$object->{fragment},"\n";
-steve
More information about the Biodevelopers
mailing list