Section 14.1. UNIVERSAL Methods


14.1. UNIVERSAL Methods

As we define classes, we create inheritance hierarchies through the global @ISA variables in each package. To search for a method, Perl wanders through the @ISA TRee until it finds a match or fails.

After the search fails, however, Perl always looks in one special class called UNIVERSAL and invokes a method from there, if found, just as if it had been located in any other class or superclass.

One way to look at this is that UNIVERSAL is the base class from which all objects derive. Any method we place here, such as:

 sub UNIVERSAL::fandango {   warn 'object ', shift, " can do the fandango!\n"; } 

enables all objects of our program to be called as $some_object->fandango.

Generally, we should provide a fandango method for specific classes of interest and then provide a definition in UNIVERSAL::fandango as a backstop, in case Perl can't find a more specific method. A practical example might be a data-dumping routine for debugging or maybe a marshaling strategy to dump all application objects to a file. We simply provide the general method in UNIVERSAL and override it in the specific classes for unusual objects.

Obviously, we should use UNIVERSAL sparingly, because there's only one universe of objects, and our fandango might collide with some other included module's fandango. For this reason, UNIVERSAL is hardly used for anything except methods that must be completely, well, universal, like during debugging or other Perl-internal behavior that ordinary programmers may blissfully ignore.




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