Полезная информация

Advanced Perl Programming

Advanced Perl ProgrammingSearch this book
Previous: 7.2 Objects in PerlChapter 7
Object-Oriented Programming
Next: 7.4 Recap of Conventions
 

7.3 UNIVERSAL

All modules implicitly inherit from a built-in module called UNIVERSAL and inherit the following three methods:

isa (package name)

For example, Rectangle->isa('Shape') returns true if the Rectangle module inherits (however indirectly) from the Shape module.

can (function name)

Rectangle->can('draw') returns true if the Rectangle or any of its base packages contain a function called draw.

VERSION (need version)

If you say,

    package Bank;
    $VERSION = 5.1;

and the user of this module says,

    use Bank 5.2;

Perl automatically calls Bank->VERSION(5.2), which can, for instance, make sure that all libraries required for version 5.2 are loaded. The default VERSION method provided by UNIVERSAL simply dies if the Bank's $VERSION variable has a lower value than that needed by the user of the module.

Because Perl allows a package to shamelessly trample on other namespaces, some packages use the UNIVERSAL module as a holding area for some global subroutines that they wish to export to everyone. I recommend that you do not use this "feature" yourself (or at least not in those that you contribute to CPAN!).

7.3.1 Searching for Methods

We have mentioned two places that Perl searches when it cannot find a method in the target module: the inheritance hierarchy (@ISA) and AUTOLOAD. While checking the inheritance hierarchy, Perl checks the base classes' @ISA arrays too: a depth-first search is conducted, and the first available one is used. Let us examine the precise order in which all these subroutines are searched. Given:

package Man;
@ISA = qw(Mammal Social_Animal);

a call to Man->schmooze results in the following search sequence. First the normal inheritance hierarchy is checked:

  1. Man::schmooze

  2. Mammal::schmooze

  3. (Mammal's base classes, recursively)::schmooze

  4. Social_Animal::schmooze

  5. (Social_Animal's base classes, recursively)::schmooze

  6. UNIVERSAL::schmooze (because UNIVERSAL is implicitly at the end of every module's @ISA array)

Then AUTOLOAD is looked up in the same order:

  1. Man::AUTOLOAD

  2. Mammal::AUTOLOAD

  3. (Mammal's base classes, recursively)::AUTOLOAD

  4. Social_Animal::AUTOLOAD

  5. (Social_Animal's base classes, recursively)::AUTOLOAD

  6. UNIVERSAL::AUTOLOAD

The first available subroutine is given the control and the search is stopped. If all fails, Perl throws a run-time exception.


Previous: 7.2 Objects in PerlAdvanced Perl ProgrammingNext: 7.4 Recap of Conventions
7.2 Objects in PerlBook Index7.4 Recap of Conventions