Moose is an extension of the object system of the Perl programming language. Its stated purpose[1] is to bring modern object-oriented programming language features to Perl 5, and to make object-oriented Perl programming more consistent and less tedious.
Moose is built on Class::MOP
, a metaobject protocol (MOP). Using the MOP, Moose provides complete type introspection for all Moose-using classes.
Moose allows a programmer to create classes:
An attribute is a property of the class that defines it.
Roles in Moose are based on traits. They perform a similar task as mixins, but are composed horizontally rather than inherited. They are also somewhat like interfaces, but unlike some implementations of interfaces they can provide a default implementation. Roles can be applied to individual instances as well as Classes.
There are a number of Moose extension modules on CPAN. there are 855 modules in 266 distributions in the MooseX namespace.[2] Most of them can be optionally installed with the Task::Moose module.[3]
This is an example of a class Point
and its subclass Point3D
:
has 'x' => (isa => 'Num', is => 'rw');has 'y' => (isa => 'Num', is => 'rw');
sub clear
sub set_to
package Point3D;use Moose;use Carp;
extends 'Point';
has 'z' => (isa => 'Num', is => 'rw');
after 'clear' => sub ;
sub set_to
There is a new set_to
method in the Point3D
class so the method of the same name defined in the Point
class is not invoked in the case of Point3D
instances. The clear
method on the other hand is not replaced but extended in the subclass, so both methods are run in the correct order.
This is the same using the MooseX::Declare
extension:
class Point
class Point3D extends Point