Metaprogramming with Moose

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.

Modern Perl: The Book

cover image for Modern Perl: the book

The best Perl Programmers read Modern Perl: The Book.

affiliated with ModernPerl.net

Categories

Pages

About this Entry

This page contains a single entry by chromatic published on February 2, 2013 2:48 PM.

Why Unicode Normalization Matters was the previous entry in this blog.

Project "Facepalm" is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.


Sponsored by Blender Recipe Reviews and the Trendshare how to invest guide

Powered by the Perl programming language

what is programming?