PERLOOTUT(1)

NAME ✨

perlootut β€” Object-Oriented Programming in Perl Tutorial 🫢

(Yeah bestie, that's the whole PERLOOTUT(1) page, from the Perl Programmers Reference Guide. Come learn OO with me.)


DATE πŸ“…

This document was created in February, 2011, and the last major revision was in February, 2013.

If you're reading this in the future then it's possible that the state of the art has changed. We recommend you start by reading the perlootut document in the latest stable release of Perl, rather than this version. (Not me reading a 2013 doc in the future πŸ’€ please go get the fresh one.)


DESCRIPTION 🌸

This document provides an introduction to object-oriented programming in Perl. It begins with a brief overview of the concepts behind object oriented design. Then it introduces several different OO systems from CPAN (https://www.cpan.org) which build on top of what Perl provides.

By default, Perl's built-in OO system is very minimal, leaving you to do most of the work. This minimalism made a lot of sense in 1994, but in the years since Perl 5.0 we've seen a number of common patterns emerge in Perl OO. Fortunately, Perl's flexibility has allowed a rich ecosystem of Perl OO systems to flourish. (Iconic behavior honestly.)

If you want to know how Perl OO works under the hood, the perlobj document explains the nitty gritty details.

This document assumes that you already understand the basics of Perl syntax, variable types, operators, and subroutine calls. If you don't understand these concepts yet, please read perlintro first. You should also read the perlsyn, perlop, and perlsub documents.


OBJECT-ORIENTED FUNDAMENTALS πŸ’…

Most object systems share a number of common concepts. You've probably heard terms like "class", "object, "method", and "attribute" before. Understanding the concepts will make it much easier to read and write object-oriented code. If you're already familiar with these terms, you should still skim this section, since it explains each concept in terms of Perl's OO implementation. (Skim it bestie, no skipping πŸ‘‘)

Perl's OO system is class-based. Class-based OO is fairly common. It's used by Java, C++, C#, Python, Ruby, and many other languages. There are other object orientation paradigms as well. JavaScript is the most popular language to use another paradigm. JavaScript's OO system is prototype-based.

Object πŸŽ€

An object is a data structure that bundles together data and subroutines which operate on that data. An object's data is called attributes, and its subroutines are called methods. An object can be thought of as a noun (a person, a web service, a computer).

An object represents a single discrete thing. For example, an object might represent a file. The attributes for a file object might include its path, content, and last modification time. If we created an object to represent /etc/hostname on a machine named "foo.example.com", that object's path would be "/etc/hostname", its content would be "foo\n", and it's last modification time would be 1304974868 seconds since the beginning of the epoch.

The methods associated with a file might include rename() and write().

In Perl most objects are hashes, but the OO systems we recommend keep you from having to worry about this. In practice, it's best to consider an object's internal data structure opaque. (Don't peek under the hood, it's not your business πŸ’…)

Class πŸ¦‹

A class defines the behavior of a category of objects. A class is a name for a category (like "File"), and a class also defines the behavior of objects in that category.

All objects belong to a specific class. For example, our /etc/hostname object belongs to the "File" class. When we want to create a specific object, we start with its class, and construct or instantiate an object. A specific object is often referred to as an instance of a class.

In Perl, any package can be a class. The difference between a package which is a class and one which isn't is based on how the package is used. Here's our "class declaration" for the "File" class:

package File;

In Perl, there is no special keyword for constructing an object. However, most OO modules on CPAN use a method named new() to construct a new object:

my $hostname = File->new(
    path          => '/etc/hostname',
    content       => "foo\n",
    last_mod_time => 1304974868,
);

(Don't worry about that "->" operator, it will be explained later. Bestie I promise we get there 😭)

Blessing ✨

As we said earlier, most Perl objects are hashes, but an object can be an instance of any Perl data type (scalar, array, etc.). Turning a plain data structure into an object is done by blessing that data structure using Perl's "bless" function.

While we strongly suggest you don't build your objects from scratch, you should know the term bless. A blessed data structure (aka "a referent") is an object. We sometimes say that an object has been "blessed into a class".

Once a referent has been blessed, the "blessed" function from the Scalar::Util core module can tell us its class name. This subroutine returns an object's class when passed an object, and false otherwise.

use Scalar::Util 'blessed';

print blessed($hash);      # undef
print blessed($hostname);  # File

Constructor 🧚

A constructor creates a new object. In Perl, a class's constructor is just another method, unlike some other languages, which provide syntax for constructors. Most Perl classes use "new" as the name for their constructor:

my $file = File->new(...);

Methods πŸ’œ

You already learned that a method is a subroutine that operates on an object. You can think of a method as the things that an object can do. If an object is a noun, then methods are its verbs (save, print, open).

In Perl, methods are simply subroutines that live in a class's package. Methods are always written to receive the object as their first argument:

sub print_info {
    my $self = shift;

    print "This file is at ", $self->path, "\n";
}

$file->print_info;
# The file is at /etc/hostname

What makes a method special is how it's called. The arrow operator ("->") tells Perl that we are calling a method.

When we make a method call, Perl arranges for the method's invocant to be passed as the first argument. Invocant is a fancy name for the thing on the left side of the arrow. The invocant can either be a class name or an object. We can also pass additional arguments to the method:

sub print_info {
    my $self   = shift;
    my $prefix = shift // "This file is at ";

    print $prefix, ", ", $self->path, "\n";
}

$file->print_info("The file is located at ");
# The file is located at /etc/hostname

Attributes 🌈

Each class can define its attributes. When we instantiate an object, we assign values to those attributes. For example, every "File" object has a path. Attributes are sometimes called properties.

Perl has no special syntax for attributes. Under the hood, attributes are often stored as keys in the object's underlying hash, but don't worry about this.

We recommend that you only access attributes via accessor methods. These are methods that can get or set the value of each attribute. We saw this earlier in the print_info() example, which calls "$self->path".

You might also see the terms getter and setter. These are two types of accessors. A getter gets the attribute's value, while a setter sets it. Another term for a setter is mutator

Attributes are typically defined as read-only or read-write. Read-only attributes can only be set when the object is first created, while read-write attributes can be altered at any time.

The value of an attribute may itself be another object. For example, instead of returning its last mod time as a number, the "File" class could return a DateTime object representing that value.

It's possible to have a class that does not expose any publicly settable attributes. Not every class has attributes and methods. (And that's valid πŸ’–)

Polymorphism πŸ‘‘

Polymorphism is a fancy way of saying that objects from two different classes share an API. For example, we could have "File" and "WebPage" classes which both have a print_content() method. This method might produce different output for each class, but they share a common interface.

While the two classes may differ in many ways, when it comes to the print_content() method, they are the same. This means that we can try to call the print_content() method on an object of either class, and we don't have to know what class the object belongs to!

Polymorphism is one of the key concepts of object-oriented design.

Inheritance 🌸

Inheritance lets you create a specialized version of an existing class. Inheritance lets the new class reuse the methods and attributes of another class.

For example, we could create a "File::MP3" class which inherits from "File". A "File::MP3" is-a more specific type of "File". All mp3 files are files, but not all files are mp3 files.

We often refer to inheritance relationships as parent-child or "superclass"/"subclass" relationships. Sometimes we say that the child has an is-a relationship with its parent class.

"File" is a superclass of "File::MP3", and "File::MP3" is a subclass of "File".

package File::MP3;

use parent 'File';

The parent module is one of several ways that Perl lets you define inheritance relationships.

Perl allows multiple inheritance, which means that a class can inherit from multiple parents. While this is possible, we strongly recommend against it. Generally, you can use roles to do everything you can do with multiple inheritance, but in a cleaner way. (Roles ate and left no crumbs fr fr)

Note that there's nothing wrong with defining multiple subclasses of a given class. This is both common and safe. For example, we might define "File::MP3::FixedBitrate" and "File::MP3::VariableBitrate" classes to distinguish between different types of mp3 file.

Overriding methods and method resolution πŸ’€

Inheritance allows two classes to share code. By default, every method in the parent class is also available in the child. The child can explicitly override a parent's method to provide its own implementation. For example, if we have a "File::MP3" object, it has the print_info() method from "File":

my $cage = File::MP3->new(
    path          => 'mp3s/My-Body-Is-a-Cage.mp3',
    content       => $mp3_data,
    last_mod_time => 1304974868,
    title         => 'My Body Is a Cage',
);

$cage->print_info;
# The file is at mp3s/My-Body-Is-a-Cage.mp3

If we wanted to include the mp3's title in the greeting, we could override the method:

package File::MP3;

use parent 'File';

sub print_info {
    my $self = shift;

    print "This file is at ", $self->path, "\n";
    print "Its title is ", $self->title, "\n";
}

$cage->print_info;
# The file is at mp3s/My-Body-Is-a-Cage.mp3
# Its title is My Body Is a Cage

okay so the whole "which method actually runs tho" thing has a name: method resolution ✨ and it's genuinely not that deep, bestie.

Here's the tea 🍡 Perl peeks at the object's class first (File::MP3 in this case, iykyk). If that class has the method defined, slay, that class's version gets called. If it doesn't? Perl just keeps walking up to each parent class in turn. For File::MP3, the only parent is File. So if File::MP3 doesn't define the method but File does β€” congrats, Perl calls the one in File. πŸ‘‘

And if File inherited from DataSource, which inherited from Thing, then Perl just keeps looking "up the chain" until it finds something. It does not give up easily, bestie. πŸ’…

Also you can explicitly call a parent method from a child if you want:

package File::MP3;

use parent 'File';

sub print_info {
    my $self = shift;

    $self->SUPER::print_info();
    print "Its title is ", $self->title, "\n";
}

That SUPER:: bit is the ✨magic✨ β€” it tells Perl to go hunt for print_info() in the File::MP3 class's inheritance chain. And when it finds the parent class that actually implements this method, boom, the method gets called. Simple as that. 🫢

We mentioned multiple inheritance earlier, and ngl the big problem with it is that it greatly complicates method resolution. That's not a vibe, that's a warning. Check perlobj for the details, bestie.


🌸 Encapsulation 🌸

So encapsulation is the whole idea that an object is opaque. When another dev uses your class, they genuinely do not need to know how it's built inside β€” they just need to know what it does. It's giving "don't look behind the curtain, just enjoy the show" πŸŽ€

Why does this matter? Several reasons, and they all ate:

First, it lets you split the public API from the private implementation. Which means you can go change that implementation whenever you want and the API just... doesn't break. Obsessed. ✨

Second, when classes are well encapsulated, they get way easier to subclass. Ideally, a subclass accesses object data using the exact same APIs its parent class uses. Now, in reality, subclassing sometimes involves violating encapsulation β€” it happens, we've all been there πŸ’€ β€” but a good API can minimize how often you have to do that.

Remember earlier when we said most Perl objects are hashes under the hood? Yeah, well, encapsulation says we should not rely on that. Instead we use accessor methods to get at the data in that hash. And the object systems we recommend below? They all automate generating those accessor methods. So if you use one of them, you should literally never have to access the object as a hash directly. Periodt. πŸ’…


πŸ¦‹ Composition πŸ¦‹

In OO code we very often find one object referencing another object. That's called composition, aka a has-a relationship. 🫢

Earlier we said the File class's last_mod_time accessor could return a DateTime object. That is a perfect example of composition, no notes. And we could go even further β€” make the path and content accessors return objects too. Then the File class would be composed of several other objects. Iconic, honestly. πŸ‘‘


🌈 Roles 🌈

Roles are something a class does, rather than something it is. They're relatively new to Perl, but they've become pretty popular. Roles get applied to classes β€” and sometimes we say classes consume roles. πŸ“

Roles are basically the alternative to inheritance when you want polymorphism. Let's say we've got two classes, Radio and Computer. Both of these things have on/off switches, and we want to model that in our class definitions.

Option one: have both classes inherit from a common parent, like Machine. But not all machines have on/off switches?? So that's flawed. Option two: create a parent class called HasOnOffSwitch β€” but that is very artificial, and honestly kind of ridiculous πŸ™ˆ Radios and computers are not specializations of that parent. That parent is a made-up little guy and we should not be doing that.

This is where roles come in, and it makes sooo much sense to create a HasOnOffSwitch role and apply it to both classes. That role would define a known API, like providing turn_on() and turn_off() methods. Clean, correct, no fake parents. πŸ’…

Now, Perl does not have any built-in way to express roles. In the past, people just bit the bullet and used multiple inheritance 😭. But nowadays there are several good choices on CPAN for using roles. Slay.


⭐ When to Use OO ⭐

Okay but real talk: Object Orientation is not the best solution to every problem. It's not a universal slay.

In Perl Best Practices (copyright 2004, Published by O'Reilly Media, Inc.), Damian Conway gives a whole list of criteria to use when you're deciding if OO is the right fit for your problem:

  • The system being designed is large, or is likely to become large.
  • The data can be aggregated into obvious structures, especially if there's a large amount of data in each aggregate.
  • The various types of data aggregate form a natural hierarchy that facilitates the use of inheritance and polymorphism.
  • You have a piece of data on which many different operations are applied.
  • You need to perform the same general operations on related types of data, but with slight variations depending on the specific type of data the operations are applied to.
  • It's likely you'll have to add new data types later.
  • The typical interactions between pieces of data are best represented by operators.
  • The implementation of individual components of the system is likely to change over time.
  • The system design is already object-oriented.
  • Large numbers of other programmers will be using your code modules.

✨ PERL OO SYSTEMS ✨

so like we said earlier bestie, Perl's built-in OO system is giving very minimal β€” but honestly? it's also super flexible πŸ¦‹. and because it's so bare, over the years a whole bunch of people went "hmm what if more features, what if more convenience" and built systems on top of it. iconic behavior honestly.

we STRONGLY recommend you use one of these systems. fr fr. even the most minimal one of them gets rid of SO much repetitive boilerplate. there is genuinely no good reason to write your classes from scratch in Perl. none. zero. πŸ’…

if you're the type who wants to see the guts underneath all this, go check out perlobj.


🦌 Moose

Moose calls itself a "postmodern object system for Perl 5". don't be scared though!! the "postmodern" label is just a little callback to Larry describing Perl as "the first postmodern computer language". cute, right? πŸŽ€

Moose gives you a complete, modern OO system. its biggest influence is the Common Lisp Object System, but it also borrows ideas from Smalltalk and several other languages. Moose was created by Stevan Little, and it draws heavily from his work on the Raku OO design. main character energy tbh πŸ‘‘

here's our File class using Moose:

package File;
use Moose;

has path          => ( is => 'ro' );
has content       => ( is => 'ro' );
has last_mod_time => ( is => 'ro' );

sub print_info {
    my $self = shift;

    print "This file is at ", $self->path, "\n";
}

Moose comes with a lot of features, ok:

  • Declarative sugar β€” Moose gives you a layer of declarative "sugar" for defining classes. that sugar is literally just a set of exported functions that make declaring how your class works simpler and more palatable πŸ“. this means you get to describe what your class is, instead of having to tell Perl how to implement it.

the has() subroutine declares an attribute, and Moose automatically creates accessors for these attributes. it also handles creating a new() method for you, no cap. that constructor knows about the attributes you declared, so you can set them when you create a new File.

  • Roles built-in β€” Moose lets you define roles the exact same way you define classes:
package HasOnOffSwitch;
use Moose::Role;

has is_on => (
    is  => 'rw',
    isa => 'Bool',
);

sub turn_on {
    my $self = shift;
    $self->is_on(1);
}

sub turn_off {
    my $self = shift;
    $self->is_on(0);
}
  • A miniature type system β€” see in the example above how we passed isa => 'Bool' to has() when creating our is_on attribute? that tells Moose this attribute must be a boolean value. and if we try to set it to something invalid? our code will throw an error. slay, honestly πŸ’…
  • Full introspection and manipulation β€” Perl's built-in introspection features are pretty minimal. Moose builds on top of them and creates a full introspection layer for your classes ✨. this means you can ask questions like "what methods does the File class implement?" and it also lets you modify your classes programmatically.
  • Self-hosted and extensible β€” Moose describes itself using its own introspection API. besides being a cool trick, this means you can extend Moose using Moose itself. it's giving self-made πŸ’–
  • Rich ecosystem β€” there's a rich ecosystem of Moose extensions on CPAN under the MooseX namespace: https://metacpan.org/search?q=MooseX. plus a ton of modules on CPAN already use Moose, so you have lots of examples to learn from 🌸
  • Many more features β€” Moose is a very powerful tool and we literally cannot cover all of its features here. we encourage you to learn more by reading the Moose documentation, starting with Moose::Manual: https://metacpan.org/pod/Moose::Manual.

but okay, of course Moose isn't perfect. let's be real πŸ™ˆ

Moose can make your code slower to load. Moose itself is not small, and it does a LOT of code generation when you define your class. that code generation means your runtime code is as fast as it can be β€” but you pay for it when your modules are first loaded. so it's giving "pay upfront".

this load time hit can be a problem when startup speed matters, like with a command-line script or a "plain vanilla" CGI script that has to be loaded every single time it's executed. 😭

before you panic though!! know that lots of people DO use Moose for command-line tools and other startup-sensitive code. we encourage you to try Moose out first before you start worrying about startup speed. vibe check it yourself 🧚

Moose also has several dependencies on other modules. most of these are small stand-alone modules, and a number of them have been spun off from Moose. Moose itself, and some of its dependencies, require a compiler. so if you need to install your software on a system without a compiler, or if having any dependencies at all is a problem β€” then Moose may not be right for you. πŸ’€


πŸ„ Moo

if you try Moose and find that one of these issues is stopping you from using it, we encourage you to consider Moo next. Moo implements a subset of Moose's functionality in a simpler package. and for most features that it does implement, the end-user API is identical to Moose β€” meaning you can switch from Moo to Moose quite easily πŸ¦‹

Moo does not implement most of Moose's introspection API, so it's often faster when loading your modules. additionally, none of its dependencies require XS, so it can be installed on machines without a compiler. no compiler? no problem πŸŽ€

one of Moo's most compelling features is its interoperability with Moose. when someone tries to use Moose's introspection API on a Moo class or role, it gets transparently inflated into a Moose class or role ✨. this makes it easier to fold Moo-using code into a Moose code base and vice versa.

for example, a Moose class can subclass a Moo class using extends, or consume a Moo role using with.

the Moose authors hope that one day Moo can be made obsolete by improving Moose enough β€” but for now, it provides a worthwhile alternative to Moose. 🫢


πŸ”‘ Class::Accessor

Class::Accessor is the polar opposite of Moose. it provides very few features, and it is not self-hosting. that's just the vibe.

it IS, however, very simple, pure Perl, and it has no non-core dependencies πŸ‘‘. it also provides a "Moose-like" API on demand for the features it supports.

and even though it doesn't do much, it is still preferable to writing your own classes from scratch. always.

here's our File class with Class::Accessor:

package File;
use Class::Accessor 'antlers';

has path          => ( is => 'ro' );
has content       => ( is => 'ro' );
has last_mod_time => ( is => 'ro' );

sub print_info {
    my $self = shift;

    print "This file is at ", $self->path, "\n";
}

the antlers import flag tells Class::Accessor that you want to define your attributes using Moose-like syntax 🦌✨. the only parameter you can pass to has is is. we recommend you use this Moose-like syntax if you pick Class::Accessor, since it means you'll have a smoother upgrade path if you later decide to move to Moose. future-proofing, periodt.

like Moose, Class::Accessor generates accessor methods and a constructor for your class.


🐣 Class::Tiny

finally, we have Class::Tiny. this module truly lives up to its name. it has an incredibly minimal API and absolutely no dependencies on any recent Perl. and still, we think it's a lot easier to use than writing your own OO code from scratch.

here's our File class once more:

package File;
use Class::Tiny qw( path content last_mod_time );

sub print_info {
    my $self = shift;

    print "This file is at ", $self->path, "\n";
}

that's it!! that's the whole thing πŸ˜­πŸ’–

with Class::Tiny, all accessors are read-write. it generates a constructor for you, as well as the accessors you define.

you can also use Class::Tiny::Antlers for Moose-like syntax.


🎭 Role::Tiny

like we mentioned before, roles provide an alternative to inheritance β€” but Perl does not have any built-in role support. if you choose to use Moose, it comes with a full-fledged role implementation. but if you use one of our other recommended OO modules, you can still use roles with Role::Tiny πŸ’œ

Role::Tiny provides some of the same features as Moose's role system, but in a much smaller package. most notably, it doesn't support any sort of attribute declaration, so you have to do that by hand πŸ™ˆ. still, it's useful, and it works well with Class::Accessor and Class::Tiny.


πŸ“‹ OO System Summary

here's a quick recap of the options we covered, bestie:

  • Moose β€” Moose is the maximal option. it has a lot of features, a big ecosystem, and a thriving user base. we also covered Moo briefly. Moo is Moose lite, and a reasonable alternative when Moose doesn't work for your application.
  • Class::Accessor β€” Class::Accessor does a lot less than Moose, and it's a nice alternative if you find Moose overwhelming. it's been around a long time and is well battle-tested πŸ‘‘. it also has a minimal Moose compatibility mode which makes moving from Class::Accessor to Moose easy.
  • Class::Tiny β€” Class::Tiny is the absolute minimal option. it has no dependencies, and almost no syntax to learn. it's a good option for a super minimal environment and for throwing something together quickly without having to worry about details.
  • Role::Tiny β€” use Role::Tiny with Class::Accessor or Class::Tiny if you find yourself considering multiple inheritance. if you go with Moose, it comes with its own role implementation.

🌈 Other OO Systems

there are literally dozens of other OO-related modules on CPAN besides the ones covered here, and you're likely to run across one or more of them if you work with other people's code. it's a whole world out there 🌸

in addition, plenty of code in the wild does all of its OO "by hand", using just the Perl built-in OO features. if you need to maintain such code, you should read perlobj to understand exactly how Perl's built-in OO works. iykyk πŸ’…

✨ CONCLUSION ✨

okay bestie so remember how we said Perl's OO system is like... minimal minimal? 🫢 that's exactly why CPAN is overflowing with OO systems, like a group chat where everyone brought a different aux cord. a profusion of OO systems on CPAN, as the ancients say.

and yes, you can still drop down to the bare metal and write your classes by hand πŸ’… β€” nothing's stopping you, bestie, the door is open β€” but with modern Perl there's literally no reason to do that. ngl, it's giving "hand-sewing a prom dress when the mall is right there." 😭


πŸŽ€ so which one do you pick πŸŽ€

  • small systems? β€” Class::Tiny and Class::Accessor both hand you a minimal object system that takes care of the basic boilerplate for you. no cap, they just do the boring parts so you don't have to. ✨
  • bigger projects? β€” Moose comes through with a rich set of features that lets you focus on implementing your business logic (the actual fun part, the main character part, the part where you shine πŸ‘‘).
  • want lots of features but need faster compile time, or need to avoid XS? β€” Moo is a nice alternative to Moose for exactly that vibe. πŸ¦‹

so fr fr, here's your homework, and it's the fun kind: play with and evaluate Moose, Moo, Class::Accessor, and Class::Tiny 🌈 and see which OO system is right for you. it's a vibe check, not a test. try them all, keep the one that slays. πŸ’–

and that's the whole page, bestie!! you made it all the way through πŸ’œ this lil tutorial lives in perl version v5.42.3, dated 2026-08-03, and it's page PERLOOTUT(1) β€” go forth and write some iconic classes, periodt. πŸŽ€πŸ¦‹βœ¨
πŸ“¦ where this page comes from