advanced intermediate

How to create a simple class with Moo

Question

How do I create a basic object-oriented class using Moo in Perl?

Moo is a minimalist object-oriented framework for Perl. Here's how to create a simple class:

package Person;
use Moo;

has 'name' => (
    is => 'ro',
    required => 1,
);

has 'age' => (
    is => 'rw',
    default => 0,
);

sub greet {
    my $self = shift;
    return "Hello, I'm " . $self->name . " and I'm " . $self->age . " years old.";
}

1;

# Usage:
package main;
my $person = Person->new(name => 'Alice', age => 30);
print $person->greet(), "\n";
$person->age(31);
print "New age: ", $person->age, "\n";

Output:

Hello, I'm Alice and I'm 30 years old.
New age: 31

The has keyword defines attributes. is => 'ro' makes it read-only, is => 'rw' makes it read-write. The required => 1 parameter ensures the attribute must be provided during object construction.

Was this helpful?