Even though Moose is pretty much the right way to do object oriented programming in modern Perl these days (and for the time being, Moo is the preferred lightweight alternative to start with and upgrade to Moose transparently when you need a full set of antlers), Moose isn't only an object system.
That is, Moose isn't just a way to hide the syntax of defining classes and attributes. Moose is an object system built on top of a metaobject system. That's a fancy of way of saying "You know how you have classes and objects? And you can manipulate objects by creating them, giving their attributes values, and calling methods on them? Yeah, you can do the same thing with classes."
When you write:
package MyClass;
use Moose;
has 'attribute', is => 'ro', default => 'my value';
__PACKAGE__->meta->make_immutable;
... Moose creates a new object of the class Moose::Meta::Class.
That object represents your new class. Moose adds an attribute named
attribute
by calling the method add_attribute()
on
the metaclass instance. Moose also performs some bookkeeping and optimizations
when you call make_immutable()
on the metaclass. (That's the final
line of code in the example.)
Moose hides all of this behavior behind the has()
function it
exports when you write use Moose;
. It does something similar for
extends()
(use a superclass) and with()
(apply a
role). These exported functions are syntactic sugar around manipulating
metaclass information directly.
Because Moose makes its metaobject system (or MOP, metaobject protocol) available, you can create your own metaclass directly and manipulate its attributes and methods and roles yourself. Just as Moose makes object oriented programming in Perl easier, Moose's MOP makes metaprogramming—creating your own object system—easier.
I'll show some examples in upcoming articles.