Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 43 ยท Object-Oriented Perl

Inheritance, Roles and Moo

Learn Perl inheritance with use parent and @ISA, method resolution order, can/isa/DOES, roles, Moo and Moose attributes, and the new class feature.

In Classes and Objects you built classes by hand with bless. Real programs rarely stop at one class. A Dog is an Animal, a Report can be sent by email or saved to disk, and several unrelated classes may all need a to_json method. Perl gives you two tools for sharing behavior: inheritance (one class builds on another) and roles (a bundle of methods you compose into a class).

This lesson covers classic inheritance with use parent and @ISA, how Perl decides which method to call, the introspection methods can, isa and DOES, the CPAN modules Moo and Moose that remove most of the boilerplate, roles, and the new built-in class feature.

Perl is not installed on this site, so the Perl code below is read-only. The interactive examples are Python stand-ins that show the same ideas (method lookup order, super, and composing behavior), and each one says how it maps to Perl. Moo and Moose are CPAN modules, so their examples are shown for reading only.

Inheritance with use parent

A Perl class is just a package. Inheritance is a list of other package names stored in the package array @ISA ("is a"). When you call a method that the object's own package does not define, Perl searches the packages in @ISA.

The tidy way to fill @ISA is the parent pragma:

PERL
use v5.36;

package Animal {
    sub new ($class, %args) {
        return bless { name => $args{name} // 'unknown' }, $class;
    }
    sub name  ($self) { return $self->{name} }
    sub speak ($self) { return sprintf '%s makes a sound.', $self->name }
}

package Dog {
    use parent -norequire, 'Animal';

    sub fetch ($self) { return $self->name . ' fetches the ball.' }
}

my $rex = Dog->new(name => 'Rex');
say $rex->speak;    # Rex makes a sound.
say $rex->fetch;    # Rex fetches the ball.
TEXT
Rex makes a sound.
Rex fetches the ball.

Dog defines no new and no speak, yet both work: Perl looks in Dog, finds nothing, then looks in Animal. The bless call inside Animal::new uses the $class argument, which is Dog, so the object is a Dog even though the constructor lives in Animal. That is why constructors should always bless into $class and never into a hard-coded name.

-norequire tells parent not to try loading Animal.pm from disk, which is right when both packages live in the same file. In a real project each class has its own .pm file and you write use parent 'Animal'; so the file is loaded for you.

Two ways to share code

Inheritance A class builds on a parent class.
Roles A bundle of methods composed into a class.

Inheritance says "is a". A role says "can do".

1 / 2

Overriding methods and calling SUPER

A subclass can override a method by defining one with the same name. To extend the parent's behavior instead of replacing it, call $self->SUPER::method(...):

PERL
package Puppy {
    use parent -norequire, 'Dog';

    sub speak ($self) {
        my $base = $self->SUPER::speak();
        return "$base Yip!";
    }
}

say Puppy->new(name => 'Bit')->speak;   # Bit makes a sound. Yip!

SUPER is resolved relative to the package where the method was written, not the class of the object. So SUPER::speak inside Puppy always means "look in Puppy's parents", which keeps it correct even when someone subclasses Puppy later.

The same pattern is common in constructors: call the parent's new first, then add your own fields.

PERL
package Dog {
    sub new ($class, %args) {
        my $self = $class->SUPER::new(%args);   # the Animal part
        $self->{tricks} = [];                   # the Dog part
        return $self;
    }
}

Because $class is passed along, the object is still blessed into the most specific class, even though Animal::new did the blessing.

Method resolution order

With a single parent the search is a straight line. With several parents (use parent 'A', 'B') Perl has to pick an order. The default is depth-first, left-to-right: look in the class, then in the first parent and all of its ancestors, then in the second parent, and so on.

That works until a "diamond" appears: D inherits from B and C, and both inherit from A. Depth-first visits D, B, A, C, so A's version of a method is found before C's override, which is usually surprising. Perl offers the C3 algorithm, the same one Python uses, which keeps every class before its parents:

PERL
package D {
    use mro 'c3';
    use parent -norequire, 'B', 'C';
}

say join ' > ', @{ mro::get_linear_isa('D') };   # D > B > C > A

With C3 you can also write $self->next::method(@_) to continue to "the next class in the order", which is what cooperative multiple inheritance needs. The diagram below shows the two orders for the diamond.

flowchart TD
    D["D"] --> B["B"]
    D --> C["C"]
    B --> A["A"]
    C --> A

The diamond: depth-first order is D, B, A, C. C3 order is D, B, C, A.

Try the same shape in Python, whose method resolution order is C3. Python calls the order the MRO, and super() follows it:

Python Diamond inheritance and super (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For most programs, avoid multiple inheritance. If you find yourself reaching for it, a role is almost always the better answer.

Asking objects what they can do

Perl gives every object three methods through the universal base class UNIVERSAL:

Method Question it answers
$obj->isa('Animal') Is this object's class Animal or a subclass of it?
$obj->can('fetch') Does it have a method with this name? Returns the code reference, or false.
$obj->DOES('Logger') Does it fulfil the role or interface Logger? By default the same as isa.
PERL
say $rex->isa('Animal') ? 'yes' : 'no';   # yes
say $rex->can('fetch')  ? 'yes' : 'no';   # yes
say $rex->can('fly')    ? 'yes' : 'no';   # no

if (my $m = $rex->can('speak')) {
    say $rex->$m();                       # call the code ref as a method
}

can is the polite way to support "duck typing": ask whether the method exists instead of checking the class name. DOES was added so that a class can claim to play a role even though it does not inherit from anything. Role modules override DOES for you.

These are method calls, so they only work on blessed references and on class names. Calling isa on a plain unblessed hash reference dies. When the value might be anything, use Scalar::Util::blessed($x) && $x->isa('Animal').

Moo and Moose: less boilerplate

Hand-written constructors and accessors are repetitive. The CPAN modules Moo and Moose generate them from declarations. Moose is the full-featured meta-object system; Moo is a small, fast subset that covers most needs and starts quickly, so it is the usual choice for new code. They look almost the same:

PERL
package Animal {
    use Moo;
    use Types::Standard qw(Str Int);

    has name => (is => 'ro', isa => Str, required => 1);
    has legs => (is => 'ro', isa => Int, default => 4);
    has mood => (is => 'rw', default => 'calm');

    sub speak { my $self = shift; return $self->name . ' makes a sound.' }
}

package Bird {
    use Moo;
    extends 'Animal';

    has '+legs' => (default => 2);

    around speak => sub {
        my ($orig, $self, @args) = @_;
        return $self->$orig(@args) . ' Tweet!';
    };
}

my $b = Bird->new(name => 'Kiwi');
say $b->speak;    # Kiwi makes a sound. Tweet!
say $b->legs;     # 2

Each has line declares an attribute:

  • is => 'ro' makes a read-only accessor, 'rw' a read-write one.
  • required => 1 makes the constructor die if the attribute is missing.
  • default (or builder, and lazy to delay it) supplies a value.
  • isa checks the value; Types::Standard provides ready-made type constraints.
  • extends replaces use parent, and has '+legs' changes an inherited attribute.

The keywords before, after and around are method modifiers. They wrap an existing method without editing it, which is how a subclass can add logging or validation cleanly. The generated constructor accepts a hash or hash reference, and you hook into construction with BUILD (runs after the object is made) and BUILDARGS (rewrites the arguments).

Roles

A role is a set of methods (and optionally attributes) that a class consumes. Unlike a parent class, a role is not part of the inheritance chain; its methods are copied into the consuming class. A role can also demand that the class provide certain methods with requires:

PERL
package Role::Describable {
    use Moo::Role;
    requires 'name';                       # the class must supply this

    sub describe { my $self = shift; return 'I am ' . $self->name }
}

package Role::Loud {
    use Moo::Role;
    around describe => sub {
        my ($orig, $self) = @_;
        return uc $self->$orig();
    };
}

package Robot {
    use Moo;
    has name => (is => 'ro', required => 1);
    with 'Role::Describable';
}

say Robot->new(name => 'Ada')->describe;   # I am Ada
say Robot->new(name => 'Ada')->DOES('Role::Describable') ? 'yes' : 'no';   # yes

If two roles supply a method with the same name, composition is an error unless the class defines the method itself, which resolves the clash on purpose. That strictness is the main advantage over multiple inheritance, where the winner is picked silently by search order.

A good rule of thumb: use inheritance when the child really is a specialised version of the parent and shares its data; use a role when the behavior is a capability that unrelated classes can have.

Python A role as a checked mixin (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The new class feature

Since Perl 5.38 there is a built-in object system behind use feature 'class'. It is still marked experimental, so using it prints a warning unless you turn that category off, and details can change between releases. Check perldoc perlclass for what your Perl supports.

PERL
use v5.38;
use feature 'class';
no warnings 'experimental::class';

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

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

class Point3D :isa(Point) {
    field $z :param = 0;

    method to_string {
        my $base = $self->SUPER::to_string();
        return "$base z=$z";
    }
}

my $p = Point3D->new(x => 1, y => 2, z => 3);
say $p->move(1, 1)->to_string;

The pieces to notice:

  • class declares a package and its constructor new for you. There is no bless and no hash: object data lives in fields, which are private lexical variables.
  • field $x :param creates a field that is filled from the constructor argument x; the = 0 is its default.
  • method is like sub, but $self is set up for you and the fields are directly visible inside it.
  • :isa(Point) sets the parent class.
  • Newer releases add more: a :reader attribute on a field creates a read-only accessor (from 5.40), and the ADJUST block runs code after construction.

Because fields are not hash keys, nothing outside the class can poke at $self->{x}. That strong encapsulation is the main promise of the feature. Moo and Moose remain the safe choice today for production code that has to run on older Perls.

Choosing a style

For a small script, a plain blessed hash is fine. For code you share or maintain, prefer Moo with roles: it is small, widely used and well documented. Reach for Moose when you need its meta-object features. Try class for new code on a recent Perl where experimental status is acceptable. Whichever you choose, keep hierarchies shallow: one or two levels of inheritance, with roles for everything else.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does Perl search when you call a method that the object's own package does not define?

    Perl looks at the class, then walks the packages in @ISA (set by use parent or extends) using the method resolution order.
  2. 2. What does -norequire do in use parent -norequire, 'Animal';?

    Without the flag, parent runs require on the package name, which fails when the package lives in the current file rather than in Animal.pm.
  3. 3. What is the main difference between a role and a parent class?

    A role is not part of the inheritance chain. Its methods are copied into the consuming class, and a name conflict between two roles must be resolved explicitly.
  4. 4. Which call checks that an object has a method named fly without calling it?

    can returns the code reference when the method exists and a false value otherwise. isa and DOES check class or role names, not method names.
  5. 5. Which statement about use feature 'class' is true?

    The class feature gives fields, methods and :isa for inheritance, with data kept in private lexical fields. It is experimental and only exists in Perl 5.38 and later.

Summary

  • use parent fills @ISA; methods are searched in the class and then its parents. Always bless into $class so subclasses get objects of the right type.
  • SUPER::method calls the parent's version, resolved from the package where the code was written.
  • The default method resolution order is depth-first; use mro 'c3' gives the more predictable C3 order and next::method.
  • can, isa and DOES let you inspect objects; prefer can over checking class names.
  • Moo (and Moose) generate constructors and accessors with has, support extends, with, and before/after/around modifiers.
  • Roles bundle behavior, can require methods, and report conflicts instead of silently choosing a winner.
  • The class feature (Perl 5.38+, experimental) offers fields and methods with real encapsulation.

Next, learn to prove your classes work in Testing with Test::More.