Skip to Content
Programming Perl, 4th Edition
book

Programming Perl, 4th Edition

by Tom Christiansen, brian d foy, Larry Wall, Jon Orwant
February 2012
Intermediate to advanced
1184 pages
37h 17m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 4th Edition

Generating Accessors with Autoloading

As we mentioned earlier, when you invoke a nonexistent method, Perl has two different ways to look for an AUTOLOAD method, depending on whether you declared a stub method. You can use this property to provide access to the object’s instance data without writing a separate function for each instance. Inside the AUTOLOAD routine, the name of the method actually invoked can be retrieved from the $AUTOLOAD variable. Consider the following code:

use Person;
$him = Person–>new;
$him–>name("Aragorn");
$him–>race("Man");
$him–>aliases( ["Strider", "Estel", "Elessar"] );
printf "%s is of the race of %s.\n", $him–>name, $him–>race;
print "His aliases are: ", join(", ", @{$him–>aliases}), ".\n";

As before, this version of the Person class implements a data structure with three fields: name, race, and aliases:

package Person; use Carp; my %Fields = ( "Person::name" => "unnamed", "Person::race" => "unknown", "Person::aliases" => [], ); # The next declaration guarantees we get our own autoloader. use subs qw(name race aliases); sub new { my $invocant = shift; my $class = ref($invocant) || $invocant; my $self = { %Fields, @_ }; # clone like Class::Struct bless $self, $class; return $self; } sub AUTOLOAD { my $self = shift; # only handle instance methods, not class methods croak "$self not an object" unless ref($self); my $name = our $AUTOLOAD; return if $name =~ /::DESTROY$/; unless (exists $self–>{$name}) { croak "Can't access '$name' field in $self"; } if (@_) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Perl, 3rd Edition

Programming Perl, 3rd Edition

Larry Wall, Tom Christiansen, Jon Orwant
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes
Learning Perl, 8th Edition

Learning Perl, 8th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix

Publisher Resources

ISBN: 9781449321451Supplemental ContentErrata Page