Section 14.3. AUTOLOAD as a Last Resort


14.3. AUTOLOAD as a Last Resort

After Perl searches the inheritance tree and UNIVERSAL for a method, it doesn't just stop there if the search is unsuccessful. Perl repeats the search through the very same hierarchy (including UNIVERSAL), looking for a method named AUTOLOAD.

If an AUTOLOAD exists, the subroutine is called in place of the original method, passing it the normal predetermined argument list: the class name or instance reference, followed by any arguments provided to the method call. The original method name is passed in the package variable called $AUTOLOAD (in the package where the subroutine was compiled) and contains the fully qualified method name, so we should generally strip everything up to the final double colon if we want a simple method name.

The AUTOLOAD subroutine can execute the desired operation itself, install a subroutine and then jump into it, or perhaps just die if asked to perform an unknown method.

One use of AUTOLOAD defers the compilation of a large subroutine until it is actually needed. For example, suppose the eat method for an animal is complex but unused in nearly every invocation of the program. We can defer its compilation as follows:

 ## in Animal sub AUTOLOAD {   our $AUTOLOAD;   (my $method = $AUTOLOAD) =~ s/.*:://s; # remove package name   if ($method eq "eat") {     ## define eat:     eval q{       sub eat {         ...         long         definition         goes         here         ...       }     };                # End of eval's q{  } string     die $@ if $@;                        # if typo snuck in     goto &eat;                           # jump into it   } else {                               # unknown method     croak "$_[0] does not know how to $method\n";   } } 

If the method name is eat, we'll define eat (which we had previously in a string but had not compiled) and then jump into it with a special construct that replaces the current subroutine invocation of AUTOLOAD with an invocation of eat, just as if we invoked &eat instead of AUTOLOAD.[*] After the first AUTOLOAD hit, the eat subroutine is now defined, so we won't be coming back here. This is great for compile-as-you-go programs because it minimizes startup overhead.

[*] Although goto is generally (and rightfully) considered evil, this form of goto, which gives a subroutine name as a target, is not really the evil goto; it's the good goto. In particular, this is the "magic goto." Its trick is that AUTOLOAD is completely invisible to the subroutine.

For a more automated way of creating code to do this, which makes it easy to turn the autoloading off during development and debugging, see the AutoLoader and SelfLoader core module documentation.




Intermediate Perl
Intermediate Perl
ISBN: 0596102062
EAN: 2147483647
Year: N/A
Pages: 238

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net