February 2012
Intermediate to advanced
1184 pages
37h 17m
English
We’ve told you about Perl’s built-in object system, but there’s another object
system that Perl programmers like. The Moose CPAN module uses metaobject programming to
do a lot of fancy things for you. There’s a lot more to Moose than we can tell you about in this book (and it really
deserves its own book anyway), but here’s a taste:
use v5.14;
package Stables 1.01 {
use Moose;
has "animals" => (
traits => ["Array"],
is => "rw",
isa => "ArrayRef[Animal]",
default => sub { [] },
handles => {
add_animal => "push",
add_animals => "push",
},
);
sub roll_call {
my($self) = @_;
for my $animal ($self–>animals) {
say "Some ", $animal–>type,
" named ", $animal–>name,
" is in the stable";
}
}
}
package Animal 1.01 {
use Moose;
has "name" => (
is => "rw",
isa => "Str",
required => 1,
);
has "type" => (
is => "rw",
isa => "Str",
default => "animal",
);
}
my $stables = Stables–>new;
$stables–>add_animal(
Animal–>new(name => "Mr. Ed", type => "horse")
);
$stables–>add_animals(
Animal–>new(name => "Donkey", type => "donkey"),
Animal–>new(name => "Lampwick", type => "donkey"),
Animal–>new(name => "Trigger", type => "horse" ),
);
$stables–>roll_call;Moose does many things to
simplify your life as a class designer. In the Stables package, Moose provides features that
would otherwise be boring work if you had to implement them yourself.
Calling has defines accessors with
particular properties.
There’s no explicit constructor in Stables
Read now
Unlock full access