Moose::...truction(3)
β¨ Moose::Manual::Construction β¨
okay bestie, welcome to the Moose::Manual::Construction page β it's a chapter of the Moose::Manual, all about making objects (and, sadly, un-making them) with Moose. this is from the User Contributed Perl Documentation set. π
πΈ VERSION πΈ
version 2.4000 β yeah she's current, she's cute, she's stable. π«Ά
π WHERE'S THE CONSTRUCTOR? π
DO NOT define a new() method for your classes! like, seriously. not even a little one. not even "just to be safe". put it down. π
here's the tea: when you use Moose in your class, your class literally becomes a subclass of Moose::Object. and Moose::Object? she comes with a new() method already, for you, for free. π
and if you follow the recommendations in Moose::Manual::BestPractices and make your class immutable, then you actually get a class-specific new() method that's "inlined" right into your class. iconic behaviour tbh. π
π¦ OBJECT CONSTRUCTION AND ATTRIBUTES π¦
the constructor Moose hands you accepts a hash or a hash reference of named parameters that match your attributes (well β technically they match their init_args, iykyk).
and that's literally it. this is just another way Moose keeps you from stressing about how classes are implemented under the hood. define a class, and boom β you're ready to start making objects. no boilerplate, no drama, no cap. β¨
π OBJECT CONSTRUCTION HOOKS π
Moose lets you hook into object construction, which is honestly so fun. you can:
- validate an object's state
- do some logging
- customize construction from parameters that don't match your attributes
- or maybe even allow non-hash(ref) constructor arguments
how? by creating BUILD and/or BUILDARGS methods. π
if these methods exist in your class, Moose will arrange for them to be called as part of the object construction process. she's got you. π«Ά
π BUILDARGS π
the BUILDARGS method gets called as a class method before an object is created.
it receives all of the arguments that were passed to new() as-is, and it's expected to return a hash reference. that hash reference gets used to construct the object, so it should contain keys matching your attributes' names (well, their init_args, same as always π
).
one super common use for BUILDARGS is to accommodate a non-hash(ref) calling style. like, say we want our Person class to be callable with a single argument of a social security number, like Person->new($ssn).
without a BUILDARGS method, Moose will complain, because she expects a hash or hash reference. rude of her? maybe. but we can use BUILDARGS to accommodate this calling style:
around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
if ( @_ == 1 && !ref $_[0] ) {
return $class->$orig( ssn => $_[0] );
}
else {
return $class->$orig(@_);
}
};
not me pointing at the call to $class->$orig β that's the important part bestie. it calls the default BUILDARGS in Moose::Object, and that method is the one that takes care of distinguishing between a hash reference and a plain hash for you. so you don't have to. π
π§ BUILD π§
the BUILD method is called after an object is created. there are several reasons to use a BUILD method:
one of the most common is checking that the object state is valid. like, yeah we can validate individual attributes through types, but we can't validate the state of a whole entire object that way. so:
sub BUILD {
my $self = shift;
if ( $self->country_of_residence eq 'USA' ) {
die 'All US residents must have an SSN'
unless $self->has_ssn;
}
}
another use of a BUILD method could be for logging or tracking object creation. very main character of you:
sub BUILD {
my $self = shift;
debug( 'Made a new person - SSN = ', $self->ssn, );
}
the BUILD method is called with the hash reference of the parameters passed to the constructor (after munging by BUILDARGS, obvs). this gives you a chance to do something with parameters that don't represent object attributes:
sub BUILD {
my $self = shift;
my $args = shift;
$self->add_friend(
My::User->new(
user_id => $args->{user_id},
)
);
}
π BUILD and parent classes π
okay this is the part where things get weird and you need to pay attention, bestie.
the interaction between multiple BUILD methods in an inheritance hierarchy is different from normal Perl methods. so:
you should never call$self->SUPER::BUILD, and you should never apply a method modifier toBUILD.
roles are the exception to this rule though! it's completely acceptable to apply a method modifier to BUILD in a role β you can even provide an empty BUILD subroutine in a role so the role is applicable even to classes without their own BUILD. slay. π
Moose arranges to have all of the BUILD methods in a hierarchy called when an object is constructed, going from parents to children. this might be surprising at first, because it reverses the normal order of method inheritance. it's giving chaos but make it intentional.
the theory behind this is that BUILD methods can only be used for increasing specialization of a class's constraints, so it makes sense to call the least specific BUILD method first. also, this is how Perl 6 does it. so there. π«Ά
πΈ OBJECT DESTRUCTION πΈ
Moose provides a hook for object destruction with the DEMOLISH method.
and, same as with BUILD: you should never explicitly call $self->SUPER::DEMOLISH. Moose will arrange for all of the DEMOLISH methods in your hierarchy to be called, going from most to least specific this time.
each DEMOLISH method is called with a single argument. this is a boolean value indicating whether or not this method was called as part of the global destruction process (that's when the Perl interpreter exits, for the record).
in most cases though? Perl's built-in garbage collection is sufficient, and you won't need to provide a DEMOLISH method at all. so don't add one just to feel something. π
π Error Handling During Destruction π
the interaction of object destruction and Perl's global $@ and $? variables can be very confusing. like, genuinely. buckle up.
Moose always localizes $? when an object is being destroyed. this means that if you explicitly call exit, that exit code will be preserved even if an object's destructor makes a system call. she's protecting you. π«Ά
Moose also preserves $@ against any eval calls that may happen during object destruction. however β if an object's DEMOLISH method actually dies, Moose explicitly rethrows that error. no quietly swallowing it, no sweeping it under the rug. π
if you do not like this behavior, you will have to provide your own DESTROY method and use that instead of the one provided by Moose::Object. you can do this to preserve $@ and capture any errors from object destruction by creating an error stack. your build, your rules. β¨
π 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>
π 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!! this was perl v5.42.0, dated 2025-07-25, and it's the Moose::...truction(3) page β go forth and construct (and occasionally demolish) responsibly. mwah. π
β¨π¦
π¦ 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