DavidSzczesniak
12/22/2017 - 11:48 AM

Attributes

An attribute is a property that every member of a class has. They can be thought of as a named value (as in a hash) that can be read and set. However, attributes can also have defaults, type constraints, delegation and much more. In other languages, they are often known as slots or properties.

\!h # Firstly, to declare use the 'has' function:
package Person;

use Moose; 
# all 'Person' objects will now have an optinal read-write 'first_name' attribute:
has 'first_name' => (is => 'rw'); # can also be 'ro' for read-only

\!h # Accessor methods:
# Lets you read and write the value of that attribute for an object.
# By default, the accessor method has the same name as the attribute.
# So, we now have a first_name accessor that can read or write a 'Person' object's first_name attribute's value.
# To explicitly specify the method names to be used for reading and writing an attribute's value:
has 'weight' => (
  is => 'ro',
  writer => '_set_weight', 
);
# handy when you want an attribute publicly readable but only privately settable.

# Following best practises, provide names for both reader and writer methods:
has 'weight' => (
  is => 'rw',
  reader => 'get_weight',
  writer => 'set_weight', 
);