10.15. Trapping Undefined Function Calls with AUTOLOADProblemYou want to intercept calls to undefined functions so you can handle them gracefully. Solution
Declare a function 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 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
The technique using typeglob assignments shown in
Recipe 10.14
is faster and more flexible than using { local *yellow = \&violet; local (*red, *green) = (\&green, \&red); print_stuff(); }
While
Aliasing subroutines like this won't handle calls to undefined subroutines. See AlsoThe 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 |
|