Moose::Manual::FAQ(3)
๐ธ Moose::Manual::FAQ โ Frequently asked questions about Moose ๐
okay bestie, pull up a chair, we're doing the Moose FAQ. this is Moose::Manual::FAQ(3), from the User Contributed Perl Documentation, and it's literally the group chat of Perl OO. let's go โจ
๐ NAME
Moose::Manual::FAQ โ Frequently asked questions about Moose ๐ฆ
๐ VERSION
version 2.4000 โ no cap, that's the one we're on ๐
๐ฌ FREQUENTLY ASKED QUESTIONS
๐ Module Stability
โจ Is Moose "production ready"?
YES bestie!! ๐ Like, so many sites with household names are out here using Moose to build high-traffic services. Countless others are using Moose in production too. Peep <http://moose.iinteractive.com/about.html#organizations> for a partial list โ it's giving "we've been booked and busy."
As of this writing, Moose is a dependency of several hundred CPAN modules. <https://metacpan.org/requires/module/Moose> โ several. hundred. ๐ญ iconic behaviour fr fr.
โจ Is Moose's API stable?
Yes. ๐ซถ The sugary API โ the one 95% of users will actually interact with โ is very stable. Any changes will be 100% backwards compatible. no breaking your code, we don't do that here.
The meta API is less set in stone tho. We reserve the right to tweak parts of it to improve efficiency or consistency. This will not be done lightly, okay? We do perform deprecation cycles. We really do not like making ourselves look bad by breaking your code. Submitting test cases is the best way to ensure that your code is not inadvertently broken by refactoring. ๐
โจ I heard Moose is slow, is this true?
Again, this one is tricky, so... Yes and No. ๐
Firstly, nothing in life is free, and some Moose features do cost more than others. It is also the policy of Moose to only charge you for the features you use, and to do our absolute best to not place any extra burdens on the execution of your code for features you are not using. Of course using Moose itself does involve some overhead, but it is mostly compile time. At this point we do have some options available for getting the speed you need. ๐ฅ
Currently we provide the option of making your classes immutable as a means of boosting speed. This will mean a slightly larger compile time cost, but the runtime speed increase (especially in object construction) is pretty significant. This can be done with the following code:
MyClass->meta->make_immutable();
๐ ๏ธ Constructors
โจ How do I write custom constructors with Moose?
Ideally, you should never write your own new method, and should use Moose's other features to handle your specific object construction needs. Here are a few scenarios, and the Moose way to solve them; ๐
If you need to call initialization code post instance construction, then use the BUILD method. This feature is taken directly from Perl 6. Every BUILD method in your inheritance chain is called (in the correct order) immediately after the instance is constructed. This allows you to ensure that all your superclasses are initialized properly as well. This is the best approach to take (when possible) because it makes subclassing your class much easier. ๐ฆ
If you need to affect the constructor's parameters prior to the instance actually being constructed, you have a number of options.
To change the parameter processing as a whole, you can use the BUILDARGS method. The default implementation accepts key/value pairs or a hash reference. You can override it to take positional args, or any other format.
To change the handling of individual parameters, there are coercions (See the Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion for a complete example and explanation of coercions). With coercions it is possible to morph argument values into the correct expected types. This approach is the most flexible and robust, but does have a slightly higher learning curve. ๐
โจ How do I make non-Moose constructors work with Moose?
Usually the correct approach to subclassing a non-Moose class is delegation. Moose makes this easy using the handles keyword, coercions, and lazy_build, so subclassing is often not the ideal route. โจ
That said, if you really need to inherit from a non-Moose class, see Moose::Cookbook::Basics::DateTime_ExtendingNonMooseParent for an example of how to do it, or take a look at MooseX::NonMoose in Moose::Manual::MooseX. ๐
๐ Accessors
โจ How do I tell Moose to use get/set accessors?
The easiest way to accomplish this is to use the reader and writer attribute options:
has 'bar' => (
isa => 'Baz',
reader => 'get_bar',
writer => 'set_bar',
);
Moose will still take advantage of type constraints, triggers, etc. when creating these methods. ๐
If you do not like this much typing, and wish it to be a default for your classes, please see MooseX::FollowPBP. This extension will allow you to write:
has 'bar' => (
isa => 'Baz',
is => 'rw',
);
Moose will create separate get_bar and set_bar methods instead of a single bar method. ๐ซถ
If you like bar and set_bar, see MooseX::SemiAffordanceAccessor.
NOTE: This cannot be set globally in Moose, as that would break other classes which are built with Moose. ๐ You can still save on typing by defining a newMyApp::Moosethat exports Moose's sugar and then turns onMooseX::FollowPBP. SeeMoose::Cookbook::Extending::Mooseish_MooseSugar.
โจ How can I inflate/deflate values in accessors?
Well, the first question to ask is if you actually need both inflate and deflate. ๐ค
If you only need to inflate, then we suggest using coercions. Here is some basic sample code for inflating a DateTime object:
class_type 'DateTime';
coerce 'DateTime'
=> from 'Str'
=> via { DateTime::Format::MySQL->parse_datetime($_) };
has 'timestamp' => (is => 'rw', isa => 'DateTime', coerce => 1);
This creates a custom type for DateTime objects, then attaches a coercion to that type. The timestamp attribute is then told to expect a DateTime type, and to try to coerce it. When a Str type is given to the timestamp accessor, it will attempt to coerce the value into a DateTime object using the code in found in the via block. ๐
For a more comprehensive example of using coercions, see the Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion. ๐ธ
If you need to deflate your attribute's value, the current best practice is to add an around modifier to your accessor:
# a timestamp which stores as
# seconds from the epoch
has 'timestamp' => (is => 'rw', isa => 'Int');
around 'timestamp' => sub {
my $next = shift;
my $self = shift;
return $self->$next unless @_;
# assume we get a DateTime object ...
my $timestamp = shift;
return $self->$next( $timestamp->epoch );
};
It is also possible to do deflation using coercion, but this tends to get quite complex and require many subtypes. An example of this is outside the scope of this document, ask on #moose or send a mail to the list. ๐ฌ
Still another option is to write a custom attribute metaclass, which is also outside the scope of this document, but we would be happy to explain it on #moose or the mailing list. ๐
๐ฎ Method Modifiers
โจ How can I affect the values in @_ using before?
You can't, actually: before only runs before the main method, and it cannot easily affect the method's execution. ๐ญ
You similarly can't use after to affect the return value of a method.
We limit before and after because this lets you write more concise code. You do not have to worry about passing @_ to the original method, or forwarding its return value (being careful to preserve context). โจ
The around method modifier has neither of these limitations, but is a little more verbose.
Alternatively, the MooseX::Mangle extension provides the mangle_args function, which does allow you to affect @_. ๐
โจ Can I use before to stop execution of a method?
Yes, but only if you throw an exception. ๐จ If this is too drastic a measure then we suggest using around instead. The around method modifier is the only modifier which can gracefully prevent execution of the main method. Here is an example:
around 'baz' => sub {
my $next = shift;
my ($self, %options) = @_;
unless ($options->{bar} eq 'foo') {
return 'bar';
}
$self->$next(%options);
};
By choosing not to call the $next method, you can stop the execution of the main method. ๐
Alternatively, the MooseX::Mangle extension provides the guard function, which will conditionally prevent execution of the original method.
โจ Why can't I see return values in an after modifier?
As with the before modifier, the after modifier is simply called after the main method. It is passed the original contents of @_ and not the return values of the main method. ๐ญ
Again, the arguments are too lengthy as to why this has to be. And as with before I recommend using an around modifier instead. Here is some sample code:
around 'foo' => sub {
my $next = shift;
my ($self, @args) = @_;
my @rv = $next->($self, @args);
# do something silly with the return values
return reverse @rv;
};
Alternatively, the MooseX::Mangle extension provides the mangle_return function, which allows modifying the return values of the original method. ๐
๐ง Type Constraints
โจ How can I provide a custom error message for a type constraint?
Use the message option when building the subtype:
subtype 'NaturalLessThanTen'
=> as 'Natural'
=> where { $_ < 10 }
=> message { "This number ($_) is not less than ten!" };
This message block will be called when a value fails to pass the NaturalLessThanTen constraint check. ๐
โจ Can I turn off type constraint checking?
There's no support for it in the core of Moose yet. This option may come in a future release. ๐
Meanwhile there's a MooseX extension that allows you to do this on a per-attribute basis, and if it doesn't do what you it's easy to write one that fits your use case. ๐ฆ
โจ My coercions stopped working with recent Moose, why did you break it?
Moose 0.76 fixed a case where coercions were being applied even if the original constraint passed. This has caused some edge cases to fail where people were doing something like
subtype 'Address', as 'Str';
coerce 'Address', from 'Str', via { get_address($_) };
This is not what they intended, because the type constraint Address is too loose in this case. It is saying that all strings are Addresses, which is obviously not the case. ๐ The solution is to provide a where clause that properly restricts the type constraint:
subtype 'Address', as 'Str', where { looks_like_address($_) };
This will allow the coercion to apply only to strings that fail to look like an Address. โจ
๐ญ Roles
โจ Why is BUILD not called for my composed roles?
okay so the whole reason BUILD never fires in composed roles is that roles are not order sensitive. Like, roles get composed in a way where the order of composition genuinely does not matter โ if you wanna go deep on the theory behind that, the original traits papers live over here at http://www.iam.unibe.ch/~scg/Research/Traits/. And since roles are basically unordered by nature, there is literally no way to figure out what order the BUILD methods should run in. So Moose justโฆ doesn't. ๐
But bestie, there are a couple of workarounds, don't panic:
- Use a combo of lazy and default on your attributes to defer initialization โ the Binary Tree example in the cookbook is a great demo of lazy/default usage, see
Moose::Cookbook::Basics::BinaryTree_AttributeFeatures๐ธ - Use attribute triggers, which fire after an attribute gets set, to handle initialization. They're described in the Moose docs, and you can find examples in the test suite โจ
Lowkey the real takeaway: roles should not require initialization. Full stop. They should either hand you sane defaults or be documented as needing specific initialization. And one way to "document" that is to have a separate attribute initializer that the role requires. Here's how:
package My::Role;
use Moose::Role;
has 'height' => (
is => 'rw',
isa => 'Int',
lazy => 1,
default => sub {
my $self = shift;
$self->init_height;
}
);
requires 'init_height';
In this example, the role will not compose successfully unless the class provides an init_height method. No method, no composition, no vibe. ๐
And if none of those solutions work for you? Then it's possible that a role is just not the best tool for the job, and you really should be using classes. Or at the very least, trim down the amount of functionality in your role so it doesn't require initialization at all. ๐ฆ
โจ What are traits, and how are they different from roles? โจ
In Moose, a trait is almost exactly the same thing as a role โ except that traits typically register themselves, which means you can refer to them by a short name like Big instead of the whole MyApp::Role::Big. Short king behavior, honestly. ๐
In Moose-speak: a Role is usually composed into a class at compile time, whereas a Trait is usually composed into an instance of a class at runtime, to add or modify the behavior of just that one instance. Different era, different energy.
Outside the context of Moose, traits and roles generally mean exactly the same thing. The original paper called them traits, but Perl 6 will call them roles. Same thing, different name, iconic either way. ๐
โจ Can an attribute-generated method (e.g. an accessor) satisfy requires? โจ
Yes! Just be sure to consume the role after declaring your attribute. Order matters here, bestie. "Required Attributes" in Moose::Manual::Roles has an example:
package Breakable;
use Moose::Role;
requires 'stress';
package Car;
use Moose;
has 'stress' => ( is => 'rw', isa => 'Int' );
with 'Breakable';
And if you mistakenly consume the Breakable role before declaring your stress attribute? You would see an error like this:
'Breakable' requires the method 'stress' to be implemented by 'Car' at...
Not me consuming the role too early and getting absolutely cooked ๐ญ
๐ Moose and Subroutine Attributes ๐
Why don't subroutine attributes I inherited from a superclass work?
Currently, when subclassing a module is done at runtime with the extends keyword, but attributes are checked at compile time by Perl. Those two things are on completely different schedules. ๐
To make attributes work, you must place extends in a BEGIN block so that the attribute handlers will be available at compile time, like this:
BEGIN { extends qw/Foo/ }
Heads up: we're talking about Perl's subroutine attributes here, not Moose attributes. Different creatures, same name, classic.
sub foo : Bar(27) { ... }
๐ AUTHORS ๐
- Stevan Little <stevan@cpan.org>
- Dave Rolsky <autarch@urth.org>
- Jesse Luehrs <doy@cpan.org>
- Shawn M Moore <sartak@cpan.org>
- ืืืื ืงืื'ืื (Yuval Kogman) <nothingmuch@woobling.org>
- Karen Etheridge <ether@cpan.org>
- Florian Ragwitz <rafl@debian.org>
- Hans Dieter Pearcey <hdp@cpan.org>
- Chris Prather <chris@prather.org>
- Matt S Trout <mstrout@cpan.org>
Absolute legends, every single one. ๐ซถ
๐ COPYRIGHT AND LICENSE ๐
This software is copyright (c) 2006 by Infinity Interactive, Inc.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
And that's the whole page, bestie โ that was perl v5.42.0 doing its thing on 2025-07-25, and this lil manual is Moose::Manual::FAQ(3). Go forth and compose responsibly ๐
โจ๐ธ
๐ฆ where this page comes from
- fedora 43: perl-Moose 2.4000-4.fc43 ยท GPL-1.0-or-later OR Artistic-1.0-Perl
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms