Skip to Content
Programming Perl, 4th Edition
book

Programming Perl, 4th Edition

by Tom Christiansen, brian d foy, Larry Wall, Jon Orwant
February 2012
Intermediate to advanced
1184 pages
37h 17m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 4th Edition

Method Autoloading

Normally, when you call an undefined subroutine in a package that defines an AUTOLOAD subroutine, the AUTOLOAD subroutine is called in lieu of raising an exception (see the section Autoloading in Chapter 10). With methods, this works a little differently. If the regular method search (through the class, its ancestors, and finally UNIVERSAL) fails to find a match, the same sequence is run again, this time looking for an AUTOLOAD subroutine. If found, this subroutine is called as a method, with the package’s $AUTOLOAD variable set to the fully qualified name of the subroutine on whose behalf AUTOLOAD was called.

You need to be a bit cautious when autoloading methods. First, the AUTOLOAD subroutine should return immediately if it’s being called on behalf of a method named DESTROY, unless your goal was to simulate DESTROY, which has a special meaning to Perl (see the section Instance Destructors later in this chapter).

sub AUTOLOAD {
    return if our $AUTOLOAD =~ /::DESTROY$/;
    ...
}

Second, if the class is providing an AUTOLOAD safety net, you won’t be able to use UNIVERSAL::can on a method name to check whether it’s safe to invoke. You have to check for AUTOLOAD separately:

if ($obj–>can("methname") || $obj–>can("AUTOLOAD")) {
    $obj–>methname();
}

Finally, under multiple inheritance, if a class inherits from two or more classes—each of which has an AUTOLOAD—only the leftmost will ever be triggered, since Perl stops as soon as it finds the first AUTOLOAD.

The last two quirks ...

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.
Start your free trial

You might also like

Programming Perl, 3rd Edition

Programming Perl, 3rd Edition

Larry Wall, Tom Christiansen, Jon Orwant
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes
Learning Perl, 8th Edition

Learning Perl, 8th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix

Publisher Resources

ISBN: 9781449321451Supplemental ContentErrata Page