introduction to Perl 5 for web developers Inheritance in Perl Inheritance in Perl 5 is very simple. To do so, you simply declare a class array called @ISA. This array will be used to store the name and parent class(es) of the new species. Whenever the new class is used, it will have this reference to its lineage and be able to check there against method calls and properties.

For example, to define a subclass of Cat, you could use

     package NorthAmericanCat;

     @NorthAmericanCat::ISA = ("Cat");
     sub new {
             [. . . Code goes here . . .]

Notice that in perl 5, package namespace references are handled using the "::" notation to delimit the names. For example, here NorthAmericanCat is separated from the ISA variable name via "::". Another common inheritence idiom is to make the generic abstract class be the first namespace and then the specific concrete classes become the second namespace.

If we were following this convention, we would have called the North American Cat class "Cat::NorthAmerican" rather than "NorthAmericanCat" and ISA would be defined as @Cat::NorthAmerican::ISA instead of "@NorthAmericanCat::ISA".

If this namespace stuff seems a little confusing, don't worry. Namespaces are just labels for package names. They merely provide a way to flexibly organize your classes and object names. This is similar to how you can define a directory structure for Word processing and Spreadsheet documents according to how complex and how many documents you have. If you have one or two documents, you will probably dump them all in one directory. But if you have many documents, you may organize them in a hierarchy that makes sense to you.

Similarly, if your program is simple, you will likely just dump all the package names into a flat namespace with no hierarchy. But as your programs become larger and larger and more complex, you will likely start noticing that you use "::" to separate hierarchical namespaces more often.

Finally, note that instantiation of an inherited class will work just the same as it did without inheritance.

Previous | Next | Table of Contents