Method Autoloading
Normally, when you call an undefined subroutine in a package that defines
an AUTOLOAD subroutine, the AUTOLOAD subroutine is called in lieu of
raising an exception (see the section Autoloading in
Chapter 10). With methods, this works a little
differently. If the regular method search (through the class, its
ancestors, and finally UNIVERSAL)
fails to find a match, the same sequence is run again, this time looking
for an AUTOLOAD subroutine.
If found, this subroutine is called as a method, with the package’s
$AUTOLOAD variable set to the fully
qualified name of the subroutine on whose behalf AUTOLOAD was called.
You need to be a bit cautious when autoloading methods. First, the
AUTOLOAD subroutine should return
immediately if it’s being called on behalf of a method named DESTROY, unless your goal was to simulate
DESTROY, which has a special meaning
to Perl (see the section Instance Destructors later in this
chapter).
sub AUTOLOAD {
return if our $AUTOLOAD =~ /::DESTROY$/;
...
}Second, if the class is providing an AUTOLOAD safety net, you won’t be able to use
UNIVERSAL::can on a method name to
check whether it’s safe to invoke. You have to check for AUTOLOAD separately:
if ($obj–>can("methname") || $obj–>can("AUTOLOAD")) {
$obj–>methname();
}Finally, under multiple inheritance, if a class inherits from two
or more classes—each of which has an AUTOLOAD—only the leftmost will ever be
triggered, since Perl stops as soon as it finds the first AUTOLOAD.
The last two quirks ...