- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

16.2 A Class is Simply a Package

Unlike say C++, Perl doesn't provide any special syntax for class definitions. You use a package as a class by putting method definitions into the class.

There is a special array within each package called @ISA, which says where else to look for a method if you can't find it in the current package. This is how Perl implements inheritance. Each element of the @ISA array is just the name of another package that happens to be a class package. The classes are searched for missing methods in depth-first, left-to-right order by default (see "Method Resolution Order" (mro) in the Perl Library Reference Manual (Volume 1) for alternative search order and other in-depth information). The classes accessible through @ISA are known as base classes of the current class.

All classes implicitly inherit from class UNIVERSAL as their last base class. Several commonly used methods are automatically supplied in the UNIVERSAL class; see 16.6 or UNIVERSAL ("Base class for ALL classes (blessed references)" (UNIVERSAL) in the Perl Library Reference Manual (Volume 2)) for more details.

If a missing method is found in a base class, it is cached in the current class for efficiency. Changing @ISA or defining new subroutines invalidates the cache and causes Perl to do the lookup again.

If neither the current class, its named base classes, nor the UNIVERSAL class contains the requested method, these three places are searched all over again, this time looking for a method named AUTOLOAD(). If an AUTOLOAD is found, this method is called on behalf of the missing method, setting the package global $AUTOLOAD to be the fully qualified name of the method that was intended to be called.

If none of that works, Perl finally gives up and complains.

If you want to stop the AUTOLOAD inheritance say simply


and the call will die using the name of the sub being called.

Perl classes do method inheritance only. Data inheritance is left up to the class itself. By and large, this is not a problem in Perl, because most classes model the attributes of their object using an anonymous hash, which serves as its own little namespace to be carved up by the various classes that might want to do something with the object. The only problem with this is that you can't sure that you aren't using a piece of the hash that isn't already used. A reasonable workaround is to prepend your fieldname in the hash with the package name.

sub bump {
    my $self = shift;
    $self->{ __PACKAGE__ . ".count"}++;
ISBN 9781906966027Perl Language Reference ManualSee the print edition