Multiple ways to inheritance in Perl

Mark Gardner
CodeX
Published in
4 min readNov 16, 2021

--

Inspired by my par­ents com­ing to vis­it at the end of the week, I thought I’d write about how Perl class­es can have ​”par­ents” as well, from which they inher­it meth­ods. Although it might seem on the sur­face as though there’s more than one way to do it, these tech­niques all share the same under­ly­ing mechanism.

Where it all BEGINs: @ISA

Perl class­es are just repur­posed packages, i.e., a name­space for vari­ables and sub­rou­tines. The two key dif­fer­ences are:

If you want­ed to do every­thing by hand at the low­est lev­el, you could make a sub­class at com­pile 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 intro­duced the base prag­ma (back when Perl used that kind of ver­sion­ing scheme; in these days of seman­tic ver­sion­ing we’d call it ver­sion 5.4.4). It does the above BEGIN block in a sin­gle line:

use base 'Local::MyParentClass'; # don't do this unless you're also using fields

You might see use base in old­er code espe­cial­ly if it’s also using the fields prag­ma. However, Perl devel­op­ers dis­cour­age both as the for­mer silences cer­tain mod­ule load­ing errors while the lat­ter is at odds with the object-​oriented pro­gram­ming prin­ci­ple of encap­su­la­tion.

So use parent instead, which Perl has includ­ed since ver­sion 5.10.1 in 2009:

use parent 'Local::MyParentClass';

A cou­ple of years ago my Newfold Digital col­league David Oswald cre­at­ed a fork of par­ent called parent::versioned that sup­ports spec­i­fy­ing the low­est ver­sion for super­class­es. You call…

--

--