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 likeisa(type),is(accessor type), and default values. - Perl sigils (
$,@,%) are less visible sinceMoosegenerates accessor methods you call on object instances. Mooseautomatically provides constructornew, 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 becauseisisrw. Accessors are used as methods.isaenforces type constraints; Moose will warn or die if you try to set wrong types (if run with type checking enabled).required => 1means you must supplynameduring object construction; otherwise, an error occurs.ageis 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 Mooseinside your package to enable all Moose features. - Always call
->newwith 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
Name: Alice
Age: 30
Updated Name: Bob
(empty)Was this helpful?
Related Questions
- How to use Moose::Util::TypeConstraints for custom types?
- How to implement method delegation in Perl Moo?
- How to use Type::Tiny with Moo for strict typing in Perl?
- How to use required attributes in Perl Moo and Moose?
- How to convert a Perl Moo class to Moose?
- How to use Moo lazy_build for attribute defaults in Perl?