Search⌘ K

Class Attributes

Explore how to define class attributes in Perl objects using Moose, including read-only and read-write properties, type constraints, and how these attributes manage object state. Understand the design choices behind mutability and immutability in object-oriented Perl programming.

Every Perl object is unique. Objects can contain private data associated with each unique object, often called attributes, instance data, or object state.

Defining an attribute

We define an attribute by declaring it as part of the class:

Perl
package Cat {
use Moose;
has 'name', is => 'ro', isa => 'Str';
}

Moose exports the has() function for us to use to declare an attribute. In English, this code reads as, “Cat objects have a name attribute. It’s read-only, and it’s a string.” The first argument, name, is the attribute’s name. The is => 'ro' pair of arguments declares that this ...