DavidSzczesniak
12/22/2017 - 3:08 PM

The default attribute and builder methods

Attributes can have default values, and Moose provides two ways to do that.

\!h # The 'builder' method
# This works as an alternative for using subroutine references to set default attribute values.
has 'size' => (
  is => 'ro',
  builder => '_build_size',
  predicate => 'has_size',
);
 
# Large chunk of code moved to its own named method, improving readbility
# Recommended for anything past the simplest default
sub _build_size {
  return ('small', 'medium', 'large') [int(rand 3)];
}
\!h # Simplest form - provide a non-reference scalar value for the 'default' option:

has 'size' => (
  is => 'ro',
  default => 'medium', # sets the default value to the string 'medium'
  predicate => 'has_size',
);

my $person = Person->new();
$person->size; # no value given upon construction, value now set to the attribute's default; 'medium'
$person->has_size; # true

\!h # You can also provide a subroutine reference for 'default':
has 'size' => (
  is => 'ro',
  default =>  
     sub { ('small', 'medium', 'large')[int(rand 3)]},# pick randomly between the three to determine default value each time:
  predicate => 'has_size',
);

\!h # NOTE: If you want to use any sort of reference as the default value, it must be returned from a subroutine(wrapped in sub). 
# Otherwise, Perl would instantiate the reference exactly once; it would be shared by all objects.