Trapping Undefined Function Calls with AUTOLOAD
Problem
You want to intercept calls to undefined functions so you can handle them gracefully.
Solution
Declare a function called AUTOLOAD for the package
whose undefined function calls you’d like to trap. While
running, that package’s $AUTOLOAD variable
contains the name of the undefined function being called.
Discussion
Another strategy for creating similar functions is to use a proxy
function. If you call an undefined function, instead of automatically
raising an exception, you can trap the call. If the function’s
package has a function named AUTOLOAD, then this
function is called in its place, with the special package global
$AUTOLOAD set to the fully qualified function
name. The AUTOLOAD subroutine can then do whatever
that function would do.
sub AUTOLOAD {
use vars qw($AUTOLOAD);
my $color = $AUTOLOAD;
$color =~ s/.*:://;
return "<FONT COLOR='$color'>@_</FONT>";
}
#note: sub chartreuse isn't defined.
print chartreuse("stuff");When the nonexistent main::chartreuse function is
called, rather than raising an exception,
main::AUTOLOAD is called with the same arguments
as you passed chartreuse. The package variable
$AUTOLOAD would contain the string
main::chartreuse because that’s the function
it’s proxying.
The technique using typeglob assignments shown in Section 10.14 is faster and more flexible than using
AUTOLOAD. It’s faster because you don’t have to run the copy and substitute. It’s more flexible because it lets you do this: ...
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