- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

8.11 Autoloading

If you call a subroutine that is undefined, you would ordinarily get an immediate, fatal error complaining that the subroutine doesn't exist. (Likewise for subroutines being used as methods, when the method doesn't exist in any base class of the class's package.) However, if an AUTOLOAD subroutine is defined in the package or packages used to locate the original subroutine, then that AUTOLOAD subroutine is called with the arguments that would have been passed to the original subroutine. The fully qualified name of the original subroutine magically appears in the global $AUTOLOAD variable of the same package as the AUTOLOAD routine. The name is not passed as an ordinary argument because, er, well, just because, that's why. (As an exception, a method call to a nonexistent import or unimport method is just skipped instead.)

Many AUTOLOAD routines load in a definition for the requested subroutine using eval(), then execute that subroutine using a special form of goto() that erases the stack frame of the AUTOLOAD routine without a trace. (See the source to the standard module documented in "Load subroutines only on demand" (AutoLoader) in the Perl Library Reference Manual (Volume 2), for example.) But an AUTOLOAD routine can also just emulate the routine and never define it. For example, let's pretend that a function that wasn't defined should just invoke system with those arguments. All you'd do is:

sub AUTOLOAD {
    my $program = $AUTOLOAD;
    $program =~ s/.*:://;
    system($program, @_);
}
date();
who('am', 'i');
ls('-l');

In fact, if you predeclare functions you want to call that way, you don't even need parentheses:

use subs qw(date who ls);
date;
who "am", "i";
ls '-l';

A more complete example of this is the standard Shell module, which can treat undefined subroutine calls as calls to external programs.

Mechanisms are available to help modules writers split their modules into autoloadable files. See the standard AutoLoader module described in "Load subroutines only on demand" (AutoLoader) in the Perl Library Reference Manual (Volume 2) and in "Split a package for autoloading" (AutoSplit) in the Perl Library Reference Manual (Volume 2), the standard SelfLoader modules in "Load functions only on demand" (SelfLoader) in the Perl Library Reference Manual (Volume 2), and the document on adding C functions to Perl code in "XS language reference manual" (perlxs) in the Perl C API and Internals Manual.

ISBN 9781906966027Perl Language Reference ManualSee the print edition