Method modifiers are one of the more
powerful and flexible features of
Moose. The most common types of
modifiers are before, after and
around. Before and after are really
just “hooks” to execute some code
whenever a given method is called,
either before or after, as the names
imply. For example, this would print a
string every time fire_all is called:

In an around modifier, the first
argument is the method ($orig)
instead of the object reference
($self) like in normal methods. Then,
it’s up to you to call the original
method ($self->$orig) and capture its
return value (or not) and then return.

};

The “around” modifier is quite a bit
more powerful than before and after
because it actually can change the
arguments passed to, and the data
returned from, the original method.
It also can programmatically decide
whether even to call the original
method at all.

Around modifiers actually replace the
original method, but get passed the
original method and arguments to be
able to call it within the new modifier
function, but unlike before and after,
this has to be done manually in around.
The basic blueprint of this is below, which
is an example of an around modifier

NOTE: The semicolons at the end of
the method modifier definitions in the
examples are required. Like all the keywords provided by Moose, the modifier
sugar keywords actually are function
calls and are not subroutine definitions.
The modifier definitions are all just
function calls with exactly two arguments: a string representing the name
of the method to modify and a code
reference to the actual modifier.
CodeRefs are just treated syntactically
as values like any other. It’s not important to understand this fully to use
method modifiers, but it is important to
remember to use the semicolons.

Method modifiers make a great fitwith Roles to define behaviors at aWWW.LINUXJOURNAL.COM SEPTEMBER 2011 | 133