Skip to content
Modern Perl OOP
step 1/5

Reading — step 1 of 5

Learn

~1 min readOOP and Modules

Plain bless-based OOP works but is verbose. Most modern Perl uses Moose or its lightweight cousin Moo (CPAN). Judge0's vanilla Perl 5.28 doesn't have these by default — but you should know they exist.

Moose-style class (paraphrased — won't run on Judge0 without Moose):

package Person;
use Moose;

has 'name'  => (is => 'rw', isa => 'Str');
has 'age'   => (is => 'rw', isa => 'Int');
has 'email' => (is => 'rw', isa => 'Str', required => 0);

sub greet {
    my $self = shift;
    return "Hi, I'm " . $self->name;
}

__PACKAGE__->meta->make_immutable;

Benefits: typed attributes, validation, before/after/around method modifiers, roles (mixins), introspection.

Vanilla Perl OOP (works in Judge0):

package Person;
use strict;
use warnings;

sub new {
    my ($class, %args) = @_;
    my $self = {
        name => $args{name} || die "name required",
        age  => $args{age} // 0,
    };
    bless $self, $class;
    return $self;
}

sub name { $_[0]->{name} }
sub age { $_[0]->{age} }

sub greet {
    my $self = shift;
    return "Hi, I'm " . $self->name;
}

1;

Inheritance with parent (or older base):

package Employee;
use parent 'Person';

sub new {
    my ($class, %args) = @_;
    my $self = $class->SUPER::new(%args);
    $self->{salary} = $args{salary} // 0;
    return $self;
}

sub salary { $_[0]->{salary} }

1;

SUPER::method calls the parent's version. parent adds the parent to @ISA.

Multiple inheritance is supported (use parent 'A', 'B') but discouraged. Use roles (Moose's mixin equivalent) instead in real code.

accessor-style methods without typing each:

for my $attr (qw(name age email)) {
    no strict 'refs';
    *$attr = sub {
        my $self = shift;
        $self->{$attr} = $_[0] if @_;
        return $self->{$attr};
    };
}

Generates name, age, email getter/setters with one loop. Glob assignment is dark magic — used by Class::Accessor, Moose internals, etc.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Modern Perl OOP — Perl Advanced