Multiple ways to inheritance in Perl
Inspired by my parents coming to visit at the end of the week, I thought I’d write about how Perl classes can have ”parents” as well, from which they inherit methods. Although it might seem on the surface as though there’s more than one way to do it, these techniques all share the same underlying mechanism.
Where it all BEGIN
s: @ISA
Perl classes are just repurposed package
s, i.e., a namespace for variables and subroutines. The two key differences are:
- Subroutines may expect either an object reference or the name of a class as their first argument.
- When you call a method that isn’t defined in a class, Perl will search through the special
@ISA
array in the package for the name of a class that has that method. (You can change the search order with themro
(method resolution order) pragma.)
If you wanted to do everything by hand at the lowest level, you could make a subclass at compile time like this:
package Local::MyChildClass;
BEGIN { # don't do this:
require Local::MyParentClass;
push @ISA, 'Local::MyParentClass';
}
Don’t do that though, because we have…
base
and parent
In 1997 Perl 5.004_04 introduced the base
pragma (back when Perl used that kind of versioning scheme; in these days of semantic versioning we’d call it version 5.4.4). It does the above BEGIN
block in a single line:
use base 'Local::MyParentClass'; # don't do this unless you're also using fields
You might see use base
in older code especially if it’s also using the fields
pragma. However, Perl developers discourage both as the former silences certain module loading errors while the latter is at odds with the object-oriented programming principle of encapsulation.
So use parent
instead, which Perl has included since version 5.10.1 in 2009:
use parent 'Local::MyParentClass';
A couple of years ago my Newfold Digital colleague David Oswald created a fork of parent called parent::versioned that supports specifying the lowest version for superclasses. You call…