oop beginner

How to define a Moose class with attributes in Perl?

Question

How to define a Moose class with attributes in Perl?

Defining a class with attributes in Perl using Moose is straightforward and powerful. Moose is a modern object system for Perl that simplifies class creation by providing declarative attribute definitions, type constraints, method modifiers, and more. It follows the "There's more than one way to do it" (TMTOWTDI) philosophy but encourages a clean, readable syntax.

Key Concepts of Moose

  • Attributes are declared with has, where you specify their properties like isa (type), is (accessor type), and default values.
  • Perl sigils ($, @, %) are less visible since Moose generates accessor methods you call on object instances.
  • Moose automatically provides constructor new, accessors, and proper encapsulation.

Basic Example of a Moose Class with Attributes

Here’s an example demonstrating how to define a simple Person class with attributes name and age. This example is runnable as-is with Perl (version 5.10+ is recommended for better Moose support).

use strict;
use warnings;
use feature 'say';

{
    package Person;
    use Moose;

    # Define a read-write string attribute 'name'
    has 'name' => (
        is  => 'rw',          # read-write accessor
        isa => 'Str',         # attribute type
        required => 1,        # required at construction
    );

    # Define a read-only integer attribute 'age'
    has 'age' => (
        is      => 'ro',
        isa     => 'Int',
        default => 0,         # default value if not provided
    );

    # Moose automatically provides a constructor 'new' and accessors
}

# Usage example:
my $person = Person->new( name => 'Alice', age => 30 );

say "Name: " . $person->name;   # prints: Name: Alice
say "Age: " . $person->age;     # prints: Age: 30

# Attempt to change age would fail because it is read-only
# $person->age(31); # This would throw an error

# Change the name attribute (read-write)
$person->name('Bob');
say "Updated Name: " . $person->name;

Explanation

  • has 'name' creates a string attribute with getter/setter because is is rw. Accessors are used as methods.
  • isa enforces type constraints; Moose will warn or die if you try to set wrong types (if run with type checking enabled).
  • required => 1 means you must supply name during object construction; otherwise, an error occurs.
  • age is read-only (is => 'ro') with a default value of 0, so if you omit it during construction, it defaults there.
  • The package block for the class ensures the attributes and methods are declared before usage.

Common Gotchas

  • You must use Moose inside your package to enable all Moose features.
  • Always call ->new with named parameters matching attribute names.
  • Moose adds some runtime overhead compared to plain Perl OOP but greatly improves developer productivity.
  • To clean up after your package (reduce memory), you can add __PACKAGE__->meta->make_immutable; at the end of your class for better performance; this is optional but recommended for production code.

With this setup, Moose greatly simplifies OOP in Perl, providing robust attribute management and reducing boilerplate code while adhering to Perl's flexible and expressive nature.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 187ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Name: Alice
Age: 30
Updated Name: Bob
STDERR
(empty)

Was this helpful?

Related Questions