Moose

Moose is a complete object system for Perl 5. Consider any modern object-oriented language (which Perl 5 definitely isn't). It provides keywords for attribute declaration, object construction, inheritance, and maybe more. These keywords are part of the language, and you don't care how they are implemented.

Moose aims to do the same thing for Perl 5 OO. We can't actually create new keywords, but we do offer sugar that looks a lot like them. More importantly, with Moose, you define your class declaratively, without needing to know about blessed hashrefs, accessor methods, and so on.

With Moose, you can concentrate on the logical structure of your classes, focusing on what rather than how. A class definition with Moose reads like a list of very concise English sentences.

Moose is built on top of Class::MOP, a meta-object protocol (aka MOP). Using the MOP, Moose provides complete introspection for all Moose-using classes. This means you can ask classes about their attributes, parents, children, methods, etc., all using a well-defined API. The MOP abstracts away the symbol table, looking at @ISA vars, and all the other crufty Perl tricks we know and love(?).

Moose is based in large part on the Perl 6 object system, as well as drawing on the best ideas from CLOS, Smalltalk, and many other languages.

lhp@nereida:~/projects/perl/src/perltesting/moose$ cat -n Cat.pm 
     1  use 5.010;
     2  {
     3    package Cat;
     4    use Moose;
     5    use Time::localtime;
     6  
     7    has 'name' => ( is => 'ro', isa => 'Str');
     8    has 'birth_year'  => ( is => 'ro', 
     9                           isa => 'Int', 
    10                           default => localtime->year + 1900 
    11                         );
    12  
    13    sub meow {
    14      my $self = shift; 
    15      say 'Meow!';
    16    }
    17  
    18    sub age {
    19      my $self = shift;
    20      
    21      1900+localtime->year-$self->birth_year();
    22    }
    23  }
    24  
    25  1;

Casiano Rodríguez León
Licencia de Creative Commons
Principios de Programación Imperativa, Funcional y Orientada a Objetos Una Introducción en Perl/Una Introducción a Perl
por Casiano Rodríguez León is licensed under a Creative Commons Reconocimiento 3.0 Unported License.

Permissions beyond the scope of this license may be available at http://campusvirtual.ull.es/ocw/course/view.php?id=43.
2012-06-19