Autoloading
Normally, you can’t call a subroutine that isn’t defined. However, if
there is a subroutine named AUTOLOAD in the undefined subroutine’s
package (or in the case of an object method, in the package of any of
the object’s base classes), then the AUTOLOAD subroutine
is called with the same arguments that would have been passed to the
original subroutine. You can define the AUTOLOAD subroutine to return values just
like a regular subroutine, or you can make it define the routine that
didn’t exist and then call that as if it’d been there all
along.
The fully qualified name of the original subroutine magically
appears in the package-global $AUTOLOAD variable,
in the same package as the AUTOLOAD
routine. Here’s a simple example that gently warns you about undefined
subroutine invocations instead of exiting:
sub AUTOLOAD {
our $AUTOLOAD;
warn "Attempt to call $AUTOLOAD failed.\n";
}
blarg(10); # our $AUTOLOAD will be set to main::blarg
print "Still alive!\n";Or, you can return a value on behalf of the undefined subroutine:
sub AUTOLOAD {
our $AUTOLOAD;
return "I see $AUTOLOAD(@_)\n";
}
print blarg(20); # prints: I see main::blarg(20)Your AUTOLOAD subroutine
might load a definition for the undefined subroutine using eval or require, or use the glob assignment trick
discussed earlier, and then execute that subroutine using the special
form of goto that can erase the
stack frame of the AUTOLOAD routine without a trace. Here we define the subroutine by assigning a closure to the glob: ...
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.
Read now
Unlock full access