O'Reilly logo

Learning Perl Objects, References, and Modules by Tom Phoenix, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 11. Some Advanced Object Topics

You might wonder, “do all objects inherit from a common class?” “What if a method is missing?” “What about multiple inheritance?” “How come we haven’t seen a reference to a filehandle yet?” Well, wonder no more. This chapter covers these subjects and more.

UNIVERSAL Methods

As you define classes, you 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 are derived. Any method you place here, such as:

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

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

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

Obviously, UNIVERSAL should be used sparingly because there’s ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required