Recipe 10.15. Trapping Undefined Function Calls with AUTOLOAD (Perl Cookbook)

Perl Cookbook

Perl CookbookSearch this book
Previous: 10.14. Redefining a FunctionChapter 10
Subroutines
Next: 10.16. Nesting Subroutines
 

10.15. 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 Recipe 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:

{
    local *yellow = \&violet;  
    local (*red, *green) = (\&green, \&red);
    print_stuff();
} 

While print_stuff() is running, or while in any functions it calls, anything printed in yellow will come out violet, and the red and green texts will exchange colors.

Aliasing subroutines like this won't handle calls to undefined subroutines. AUTOLOAD does.

See Also

The section on "Autoloading" in Chapter 5 of Programming Perl and in perlsub (1); the documentation for the standard modules AutoLoader and AutoSplit, also in Chapter 7 of Programming Perl; Recipe 10.12; Recipe 12.10, Recipe 13.11


Previous: 10.14. Redefining a FunctionPerl CookbookNext: 10.16. Nesting Subroutines
10.14. Redefining a FunctionBook Index10.16. Nesting Subroutines

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.