I'm using the AUTOLOADer to create class-accessor/mutator subroutines. The object attribute may or may not be editable by the calling code, so I create different subroutines depending on the editability. This is a bit like the get_/set_ style of functions, but I didn't fancy using those. (They annoy me).
Is there a better way of doing what I've done here? If you were the maintenance programmer coming after me, would you literally come after me?
Code that achieves the same thing:
Cheers
Update: Forgot to mention: This is similar-ish to what Damian Conway does in "Object Oriented Perl", p94.
See also: accessor/mutator with AUTOLOAD and How can I use AUTOLOAD to magically define get and set methods for my member data?
#!/usr/bin/perl use warnings; use strict; my $test = Foo->new(); print $test->read_only, "\n"; $test->read_only("cheese"); # Won't do anything print $test->read_only, "\n"; print $test->read_write, "\n"; $test->read_write("cheese"); print $test->read_write, "\n"; package Foo; use vars '$AUTOLOAD'; sub new { bless { read_only => { value => "foo", editable => 0, }, read_write => { value => "bar", editable => 1, } } }; sub AUTOLOAD { no strict "refs"; my ($self, $new_value) = @_; my $field_name = $AUTOLOAD; $field_name =~ s/.*:://; if(grep /^$field_name$/,keys(%$self)) { #Build a different autoloader depending on whether # the field is editable if($self->{$field_name}{editable}) { if($new_value) { $self->{$field_name}{value} = $new_val +ue; } *{$AUTOLOAD} = sub { if(2 == @_) { $self->{$field_name}{value} = +$_[1]; } return $self->{$field_name}{value}; } } else { #Really ought to make this complain if you try + setting a value. *{$AUTOLOAD} = sub { $self->{$field_name}{valu +e}; }; } return $self->{$field_name}{value}; } else { die "No such method $AUTOLOAD. Barfing\n"; } } sub DESTROY { 1; }
In reply to Subroutines with differing behaviour created from AUTOLOAD by davis
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |