Generating Attribute Methods Using AUTOLOAD

Problem

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.

Solution

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.

Discussion

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 ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.