8.5 A Few Notes About ISA


8.5 A Few Notes About @ISA

This magical @ISA variable (pronounced "is a" not "ice-uh"), declares that Cow "is a" Animal . [2] Note that it's an array, not a simple single value, because on rare occasions it makes sense to have more than one parent class searched for the missing methods . You'll learn more about that later.

[2] ISA is actually a linguistic term . Once again, Larry Wall's background as a linguist has come back to influence Perl.

If Animal also had an @ISA , you can check there too. [3] Typically, each @ISA has only one element (multiple elements means multiple inheritance and multiple headaches ), so you get a nice tree of inheritance. (There is also inheritance through UNIVERSAL and AUTOLOAD ; see the perlobj manpage for the whole story.)

[3] The search is recursive, depth-first and left to right in each @ISA .

When you turn on use strict , you'll get complaints on @ISA because it's not a variable containing an explicit package name , nor is it a lexical ( my ) variable. You can't make it a lexical variable though: it has to belong to the package to be found by the inheritance mechanism.

There are a couple of straightforward ways to handle the declaration and setting of @ISA . The easiest is to just spell out the package name:

 @Cow::ISA = qw(Animal); 

You can also allow it as an implicitly named package variable:

 package Cow; use vars qw(@ISA); @ISA = qw(Animal); 

If you're on a recent-enough Perl (5.6 or later), you can use the our declaration to shorten it to:

 package Cow; our @ISA = qw(Animal); 

However, if you think your code might be used by people stuck with Perl 5.005 or earlier, it's be best to avoid our .

If you're bringing in the class from outside, via an object-oriented module, change:

 package Cow; use Animal; use vars qw(@ISA); @ISA = qw(Animal); 

to just:

 package Cow; use base qw(Animal); 

That's pretty darn compact. Furthermore, use base has the advantage that it's performed at compile time, eliminating a few potential errors from setting @ISA at runtime, like some of the other solutions.



Learning Perl Objects, References & Modules
Learning Perl Objects, References, and Modules
ISBN: 0596004788
EAN: 2147483647
Year: 2003
Pages: 199

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net