August 1998
Intermediate to advanced
800 pages
39h 20m
English
Your object needs accessor methods to set or get its data fields, and you’re tired of writing them all out one at a time.
Carefully use Perl’s AUTOLOAD mechanism as a proxy method generator so you don’t have to create them all yourself each time you want to add a new data field.
Perl’s AUTOLOAD mechanism intercepts all possible undefined method calls. So as not to permit arbitrary data names, we’ll store the list of permitted fields in a hash. The AUTOLOAD method will check to verify that the accessed field is in that hash.
package Person;
use strict;
use Carp;
use vars qw($AUTOLOAD %ok_field);
# Authorize four attribute fields
for my $attr ( qw(name age peers parent) ) { $ok_field{$attr}++; }
sub AUTOLOAD {
my $self = shift;
my $attr = $AUTOLOAD;
$attr =~ s/.*:://;
return unless $attr =~ /[^A-Z]/; # skip DESTROY and all-cap methods
croak "invalid attribute method: ->$attr()" unless $ok_field{$attr};
$self->{uc $attr} = shift if @_;
return $self->{uc $attr};
}
sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my $parent = ref($proto) && $proto;
my $self = {};
bless($self, $class);
$self->parent($parent);
return $self;
}
1;This class supports a constructor named new, and
four attribute methods: name,
age, peers, and
parent. Use the module this way:
use Person; my ($dad, $kid); $dad = Person->new; $dad->name("Jason"); $dad->age(23); $kid = $dad->new; $kid->name("Rachel"); $kid->age(2); printf "Kid's ...Read now
Unlock full access