Constructor (object-oriented Programming) - Perl With Moose

Perl With Moose

With the Moose object system for Perl, most of this boilerplate can be left out, a default new is created, attributes can be specified, as well as whether they can be set, reset, or are required. In addition, any extra constructor functionality can be included in a BUILD method which the Moose generated constructor will call, after it has checked the arguments. A BUILDARGS method can be specified to handle constructor arguments not in hashref / key => value form.

package Person; # enable Moose-style object construction use Moose; # first name ( a string) can only be set at construction time ('ro') has first_name => (is => 'ro', isa => 'Str', required => 1); # last name ( a string) can only be set at construction time ('ro') has last_name => (is => 'ro', isa => 'Str', required => 1); # age (Integer) can be modified after construction ('rw'), and is not required # to be passed to be constructor. Also creates a 'has_age' method which returns # true if age has been set has age => (is => 'rw', isa => 'Int', predicate => 'has_age'); # Check custom requirements sub BUILD { my $self = shift; if ($self->has_age && $self->age < 18) { # no under 18s die "No under-18 Persons"; } } 1;

In both cases the Person class is instiated like this:

use Person; my $p = Person->new( first_name => 'Sam', last_name => 'Ashe', age => 42 );

Read more about this topic:  Constructor (object-oriented Programming)

Famous quotes containing the word moose:

    The moose is singularly grotesque and awkward to look at. Why should it stand so high at the shoulders? Why have so long a head? Why have no tail to speak of?
    Henry David Thoreau (1817–1862)