Last month, I introduced the Moose object system by rewriting the sample code found in the perlboot man page to use Moose. Let’s continue the discussion and look at some of the features I didn’t cover last time.
Animal House
The role Animal included attributes name and color, and actions speak and eat. You can add a birthdate attribute to the Animal with:
has ’born’ => (is => ’ro’);
Since a birthdate isn’t mutable, it’s marked as read-only. By default, this attribute accepts any scalar, so these definitions are all equally valid:
my $horse = Horse->new(born => ’yesterday’, name => ’Newbie’); my $cow = Cow->new(born => ’spring of 82’, name => ’Bessie’); my $mouse = Mouse->new(name => ’Minnie’, born => ’3/14/1929’); my $racehorse = RaceHorse->new(name => ’Slew’, born => [3, 5, 59]);
You can use the Moose type system to narrow the permissible type of the birthdate attribute:
require DateTime; has ’born’ => (is => ’ro’, isa => ’DateTime’);
The isa parameter here declares that the born parameter must be a DateTime object, or at least something that responds true to UNIVERSAL::isa($thing,"DateTime"). Now, a run-time error occurs if you try to put anything in the born attribute other than a DateTime. Hence…
my $horse = Horse->new(born => ’yesterday’, name => ’Newbie’);
… fails, but this succeeds:
my $horse = Horse->new(born => DateTime->now, name => ’Newbie’);
The DateTime string for isa refers here to the…
Please log in to view this content.
Not Yet a Member?
Register with LinuxMagazine.com and get free access to the entire archive, including: