TExcelTAD
Home › Perl › Inheritance and class

Inheritance and class

A class can inherit methods from a parent class: when a method is not found in the object's own package, Perl searches the parents. This lesson shows classic inheritance with parent, method overriding with SUPER::, and then Perl's modern class syntax.

parent and method lookup

use parent -norequire, 'Parent'; sets up inheritance (it pushes the parent onto the package's @ISA array). -norequire is needed here because the parent is defined in the same file rather than in a separate .pm file:

perl · try it yourself
use strict;
use warnings;

package Animal {
    sub new {
        my ($class, %args) = @_;
        return bless { name => $args{name}, sound => "..." }, $class;
    }
    sub name  { $_[0]{name} }
    sub speak {
        my $self = shift;
        return $self->name . " says " . $self->sound;
    }
    sub sound { "..." }
}

package Cat {
    use parent -norequire, 'Animal';
    sub sound { "Meow" }
}

package Cow {
    use parent -norequire, 'Animal';
    sub sound { "Moo" }
}

for my $pet (Cat->new(name => "Tom"), Cow->new(name => "Daisy"), Animal->new(name => "Blob")) {
    print $pet->speak, "\n";
}
print "Tom isa Animal? ", (Cat->new(name => "Tom")->isa('Animal') ? "yes" : "no"), "\n";
Tom says Meow
Daisy says Moo
Blob says ...
Tom isa Animal? yes

Cat has no new or speak, so Perl finds them in Animal. But inside speak, $self->sound starts the search again from the object's class, so each subclass's own sound is used. That is polymorphism.

Extending a parent method with SUPER::

An overriding method can call the parent's version with SUPER:::

perl · try it yourself
use strict;
use warnings;

package Account {
    sub new {
        my ($class, %args) = @_;
        return bless { owner => $args{owner}, balance => $args{balance} // 0 }, $class;
    }
    sub withdraw {
        my ($self, $amount) = @_;
        die "Insufficient funds\n" if $amount > $self->{balance};
        $self->{balance} -= $amount;
        return $self->{balance};
    }
    sub summary { my $s = shift; "$s->{owner}: $s->{balance}" }
}

package SavingsAccount {
    use parent -norequire, 'Account';
    sub new {
        my ($class, %args) = @_;
        my $self = $class->SUPER::new(%args);     # let the parent build the object
        $self->{rate} = $args{rate} // 0.02;
        return $self;
    }
    sub withdraw {
        my ($self, $amount) = @_;
        my $fee = 1;
        print "  (fee $fee applied)\n";
        return $self->SUPER::withdraw($amount + $fee);
    }
    sub summary { my $s = shift; $s->SUPER::summary() . " at " . $s->{rate} * 100 . "%" }
}

my $acct = SavingsAccount->new(owner => "Mei", balance => 100, rate => 0.03);
$acct->withdraw(20);
print $acct->summary, "\n";

my $ok = eval { $acct->withdraw(500); 1 };
print "Error: $@" unless $ok;
  (fee 1 applied)
Mei: 79 at 3%
  (fee 1 applied)
Error: Insufficient funds

The modern class feature

Perl 5.38 introduced a built-in class syntax (still marked experimental in 5.42, so you switch off its warning). It declares fields, a generated constructor and methods with far less boilerplate:

perl · try it yourself
use v5.40;
use experimental 'class';

class Point {
    field $x :param :reader = 0;
    field $y :param :reader = 0;

    method move ($dx, $dy) {
        $x += $dx;
        $y += $dy;
        return $self;
    }
    method to_string { "($x, $y)" }
}

class Point3D :isa(Point) {
    field $z :param :reader = 0;
    method to_string { "(" . $self->x . ", " . $self->y . ", $z)" }
}

my $p = Point->new(x => 1, y => 2);
say $p->move(3, 4)->to_string;
say "x is ", $p->x;

my $q = Point3D->new(x => 1, z => 9);
say $q->to_string;
(4, 6)
x is 4
(1, 0, 9)
Keyword Meaning
class NAME { ... } declares a class (and its package)
field $name a per-object variable, visible inside methods by its plain name
:param the field can be set by a named argument to new
:reader generates a read accessor method (5.40+)
method name { ... } a method; $self is available automatically, and signatures are on
:isa(Parent) inherit from another class
ADJUST { ... } code that runs after the fields are set, like a constructor body

use v5.40; turns on strict, warnings, say and signatures in one go, and use experimental 'class' enables the feature without the experimental warning.

perl · try it yourself
use v5.40;
use experimental 'class';

class Temperature {
    field $celsius :param;
    field $label;

    ADJUST {
        die "Below absolute zero!\n" if $celsius < -273.15;
        $label = $celsius >= 30 ? "hot" : $celsius <= 0 ? "freezing" : "mild";
    }
    method report { sprintf "%.1f C is %s", $celsius, $label }
}

say Temperature->new(celsius => $_)->report for 35, 12.5, -4;
say eval { Temperature->new(celsius => -300) } // "Error: $@";
35.0 C is hot
12.5 C is mild
-4.0 C is freezing
Error: Below absolute zero!

Tip: Classic bless-based classes are what you will find in most existing code and on CPAN, so you need to know them. The class feature is the future for new code once it leaves experimental status.

Test yourself

What does use parent -norequire, 'Animal'; do?

  1. Loads Animal.pm from disk
  2. Makes the current package inherit from Animal without loading a file
  3. Copies Animal's data
  4. Deletes Animal

How does an overriding method call the parent's version?

  1. parent->method()
  2. $self->SUPER::method()
  3. super()
  4. Animal::method only

In the class feature, what does field $name :param; mean?

  1. A class constant
  2. A per-object field that can be set by a name => ... argument to new
  3. A global variable
  4. A method parameter