Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 43 ยท Object-Oriented Perl

Classes and Objects

Learn object-oriented Perl from scratch: packages as classes, bless, constructors, instance and class methods, accessors, SUPER::, DESTROY and common pitfalls.

Perl's object system is small and surprising at first: there is no class keyword in classic Perl 5, and an object is not a special kind of value. An object is just a reference (usually to a hash) that has been blessed into a package. A class is a package. A method is a subroutine in that package that receives the object or the class name as its first argument. Three ideas, and that is the whole system.

Because it is so minimal, you can see exactly how objects work, and the same machinery sits underneath modern frameworks such as Moo. This lesson builds a class from scratch. You need References and Packages and Modules first.

Perl is not installed on this site, so the Perl code is read-only and its output was captured from a real run. The interactive examples are Python stand-ins showing the same ideas in a language with a class keyword.

The three ideas

Perl OOP in three rules

Class A package that holds the methods.
Object A reference blessed into the package.
Method A sub that gets the object first.

That is the entire core of the system.

1 / 2

A first class

Create lib/Animal.pm. The constructor is an ordinary subroutine, by convention called new, that builds a hash reference and blesses it.

PERL
package Animal;
use v5.36;
use Carp qw(croak);

sub new ($class, %args) {
    croak "name is required" unless defined $args{name};
    my $self = bless {
        name  => $args{name},
        sound => $args{sound} // 'makes a sound',
        legs  => $args{legs}  // 4,
    }, $class;
    return $self;
}

sub name  ($self) { return $self->{name} }
sub legs  ($self) { return $self->{legs} }
sub speak ($self) { return sprintf '%s %s.', $self->{name}, $self->{sound} }

1;

The function bless REF, CLASS attaches the class name to the reference and returns the same reference. After that, the reference knows which package its methods come from. Using $class rather than the literal 'Animal' lets subclasses reuse the constructor (see below).

Now use it:

PERL
use v5.36;
use lib 'lib';
use Animal;

my $cat = Animal->new(name => 'Tom', sound => 'meows');
say $cat->speak;       # Tom meows.
say $cat->legs;        # 4
say ref $cat;          # Animal

The arrow and how methods are called

Animal->new(...) is a class method call: the left side is a class name, a string, and it becomes the first argument ($class). $cat->speak is an instance method call: the left side is an object, and it becomes the first argument ($self). The two forms are equivalent to calling a function with an explicit first argument, which also works:

PERL
say Animal::speak($cat);       # Tom meows.  (same thing, no inheritance lookup)

The arrow form is what you should use, because it also searches parent classes. You can also call a method whose name is in a variable, or build a class name dynamically:

PERL
my $method = 'speak';
say $cat->$method;             # Tom meows.

my $class = 'Animal';
my $dog   = $class->new(name => 'Rex', sound => 'barks');

Inside a method the convention is to take the invocant first and call it $self (or $class in a class method): my $self = shift; in older code, or a signature as above.

The stand-in below does the same thing with a Python class:

Python Stand-in: a class with a constructor and methods

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.

Attributes and accessors

Perl does not hide the object's insides: $cat->{name} works from anywhere, even though it is bad manners outside the class. By convention you reach data through accessor methods, so you can change the internals later without touching callers.

PERL
sub name ($self) { return $self->{name} }

sub set_name ($self, $new) {
    $self->{name} = $new;
    return $self;                 # lets calls chain
}

Returning $self from a setter allows method chaining: $cat->set_name('Tim')->speak. Some classes use one method for both reading and writing ($obj->name and $obj->name('x')); a separate set_ method is simpler to read and to test. Modern frameworks generate accessors for you, as shown in Inheritance, Roles and Moo.

A leading underscore marks a name as internal by convention (_cache, _validate). Perl does not enforce it, but other programmers will respect it.

Class data and class methods

A lexical variable at file level is shared by every object of the class. A class method uses the class name, not an object.

PERL
package Animal;

my $count = 0;                           # one copy for the whole class

sub new ($class, %args) {
    my $self = bless { name => $args{name} }, $class;
    $count++;
    return $self;
}

sub count ($class) { return $count }     # class method
sub DESTROY ($self) { $count-- }         # runs when an object is freed
PERL
say Animal->count;                       # 0 at the start
{
    my $temp = Animal->new(name => 'Tmp');
    say Animal->count;                   # 1
}
say Animal->count;                       # 0 again: $temp left scope

Inheritance in one step

A subclass declares its parent with use parent (or our @ISA). The subclass gets every parent method and may override them. Inside an overriding method, SUPER:: calls the parent's version.

PERL
package Dog;
use v5.36;
use parent -norequire, 'Animal';         # file-less here; normally: use parent 'Animal';

sub new ($class, %args) {
    my $self = $class->SUPER::new(%args, sound => 'barks');
    $self->{tricks} = [];
    return $self;
}

sub add_trick ($self, $trick) {
    push $self->{tricks}->@*, $trick;
    return $self;
}

sub tricks ($self) { return $self->{tricks}->@* }
PERL
my $rex = Dog->new(name => 'Rex');
$rex->add_trick('sit')->add_trick('roll');

say $rex->speak;                         # Rex barks.
say join ',', $rex->tricks;              # sit,roll
say $rex->isa('Animal') ? 'is an Animal' : 'not an Animal';   # is an Animal
say $rex->can('speak') ? 'can speak' : 'cannot speak';       # can speak

$obj->isa('Class') is true when the object belongs to that class or a subclass. $obj->can('method') returns a code reference when the method exists. Because the constructor blesses into $class, calling Dog->new gives a Dog, not an Animal. The full story of inheritance, method resolution and roles is in Inheritance, Roles and Moo.

Python Stand-in: a subclass that extends the parent constructor

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.

DESTROY and object lifetime

An object is freed when its last reference disappears (see reference counting in References). Just before that, Perl calls its DESTROY method if one exists. Use it to close files, release locks or update counters, as $count-- above.

A few rules keep DESTROY safe:

  • It runs at an unpredictable moment during global destruction at program exit, so do not rely on other objects still being intact.
  • Do not die inside it unless you mean to. Wrap risky work in eval.
  • Cycles (parent points to child and child to parent) prevent DESTROY from running at all until exit. Break them with weaken.

Inspecting objects

PERL
use Scalar::Util qw(blessed reftype);

say ref $cat;                # Animal
say blessed($cat);           # Animal
say reftype($cat);           # HASH
say "$cat";                  # Animal=HASH(0x...)

ref and blessed give the class; reftype gives the underlying data type. blessed returns undef for a non-object and is the safe way to ask "is this an object at all?" (ref also returns HASH for a plain hash reference).

Common mistakes

  • Hard-coding the class in new. Write bless {...}, $class, not bless {...}, 'Animal', or subclasses break.
  • Forgetting return $self. A constructor that returns something else gives callers an undef or a number.
  • Calling a method on undef. The error is "Can't call method "speak" on an undefined value". Check what the constructor returned.
  • Calling a class method on an object, or the reverse. Be clear which one a method expects.
  • Reaching into $self->{...} from outside the class. Use accessors.
  • Naming a method like a built-in. Methods are looked up through the arrow, so it works, but a plain function call such as rename(...) would call the built-in. Another reason to prefer clear names such as set_name.

Polymorphism, encapsulation and abstraction

The textbook OOP words all map onto small Perl idioms.

Polymorphism means different classes answer the same method call in their own way. Perl needs no interface declaration: if the object has the method, the call works.

PERL
use v5.36;
package Shape  { sub new($c, %a) { bless {%a}, $c }
                 sub describe($s) { sprintf "%s with area %.2f", ref $s, $s->area } }
package Circle { our @ISA = ('Shape'); sub area($s) { 3.14159265 * $s->{r} ** 2 } }
package Square { our @ISA = ('Shape'); sub area($s) { $s->{side} ** 2 } }
package main;
say $_->describe for Circle->new(r => 1), Square->new(side => 3);
# Circle with area 3.14
# Square with area 9.00

Abstraction hides how something works behind a small interface. A parent class can declare a method that every child must provide, by dying if it is not overridden:

PERL
package Shape { sub area($s) { die ref($s) . " must implement area\n" } }

A subclass with no area then fails with Blob must implement area the first time you call describe.

Encapsulation (data hiding) keeps object data private. Perl does not enforce privacy on a blessed hash, so there are conventions and stronger tricks:

  • By convention, a leading underscore (_cache) marks internals that outsiders should not touch.
  • A closure object stores state in lexical variables that only the object's own code references can see:
PERL
package Counter {
    sub new($class) {
        my $count = 0;
        my %self = (inc => sub { ++$count }, get => sub { $count });
        return bless \%self, $class;
    }
    sub inc($s) { $s->{inc}->() }
    sub get($s) { $s->{get}->() }
}
my $c = Counter->new;
$c->inc for 1 .. 3;
say $c->get;    # 3, and nothing outside can reach $count
  • An inside-out object keeps attributes in file-level lexical hashes keyed by the object's identity, so the object itself is an empty shell. Clean up in DESTROY.
  • The class feature in new Perls makes fields truly private (see Inheritance, Roles and Moo).

Benefits are the usual ones: you can change the internals without breaking callers, and fewer places can corrupt the data. The cost is extra code (accessors) and, with closures, slightly slower method calls. Many Perl programmers accept the convention-only approach for exactly that reason.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does bless do?

    bless marks a reference as belonging to a package. Method calls on that reference are then looked up in that package.
  2. 2. In Animal->new(name => 'Tom'), what is the first argument received by new?

    The arrow passes the invocant as the first argument. For a class method call that is the class name as a string.
  3. 3. Why should a constructor use bless {...}, $class instead of bless {...}, 'Animal'?

    With $class the object takes the class used in the call, so Dog->new through an inherited constructor returns a Dog.
  4. 4. What does $self->SUPER::new(%args) do inside the Dog package?

    SUPER:: starts the method search in the parent classes of the current package, so it calls the inherited version being overridden.
  5. 5. When does Perl call an object's DESTROY method?

    Perl frees an object when its reference count drops to zero and calls DESTROY just before that.

Summary

  • A class is a package, an object is a blessed reference (usually a hash), and a method is a sub that receives the invocant first.
  • Constructors are plain subs named new that call bless {...}, $class and return the object.
  • Class->method passes the class name; $obj->method passes the object. Use the arrow so inheritance works.
  • Use accessors rather than touching $self->{...} from outside, and return $self to allow chaining.
  • Class-wide data is a file-level lexical; DESTROY runs when the last reference goes away.
  • use parent and SUPER:: give single inheritance; isa and can inspect objects.

Next, go deeper with Inheritance, Roles and Moo.