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

Get Programming Perl, 3rd Edition 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.