Skip to content
Perl

OOP with Moose

Modern object-oriented programming in Perl.

By EZ4Code Team
oopmooseclass

Code

package Animal;
use Moose;

has 'name' => (is => 'ro', isa => 'Str', required => 1);
has 'sound' => (is => 'ro', isa => 'Str', default => 'silence');

sub speak {
  my ($self) = @_;
  return $self->name . " says " . $self->sound;
}

__PACKAGE__->meta->make_immutable;
1;

# Inheritance
package Dog;
use Moose;
extends 'Animal';

has '+sound' => (default => 'Woof');

sub fetch {
  my ($self) = @_;
  return $self->name . " fetches the ball";
}

1;

# Role (mixin)
package Walkable;
use Moose::Role;

sub walk {
  my ($self) = @_;
  return $self->name . " is walking";
}

package Cat;
use Moose;
extends 'Animal';
with 'Walkable';
has '+sound' => (default => 'Meow');

1;

# Usage
my $dog = Dog->new(name => 'Rex');
print $dog->speak();   # Rex says Woof
print $dog->fetch();   # Rex fetches the ball
print $dog->walk();    # Rex is walking (from role)

Explanation

Moose is Perl's modern OO framework — provides has (attributes), extends (inheritance), with (roles/mixins), and type constraints. is => 'ro' (read-only), 'rw' (read-write). Roles are composable units of behavior (mixins). make_immutable improves performance. The + prefix overrides an inherited attribute. Moose handles constructor, accessors, and type checking automatically.

More Perl Snippets