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:
“If the Americans, in addition to the eagle and the Stars and Stripes and the more unofficial symbols of bison, moose and Indian, should ever need another emblem, one which is friendly and pleasant, then I think they should choose the grapefruit. Or rather the half grapefruit, for this fruit only comes in halves, I believe. Practically speaking, it is always yellow, always just as fresh and well served. And it always comes at the same, still hopeful hour of the morning.”
—Johan Huizinga (18721945)