February 2012
Intermediate to advanced
1184 pages
37h 17m
English
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 (@_) ...