{
    "mode": "perldoc",
    "parameter": "Moose::Manual::MethodModifiers",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Moose%3A%3AManual%3A%3AMethodModifiers/json",
    "generated": "2026-06-13T01:10:53Z",
    "sections": {
        "NAME": {
            "content": "Moose::Manual::MethodModifiers - Moose's method modifiers\n",
            "subsections": []
        },
        "VERSION": {
            "content": "version 2.2200\n\nWHAT IS A METHOD MODIFIER?\nMoose provides a feature called \"method modifiers\". You can also think of these as \"hooks\" or\n\"advice\".\n\nIt's probably easiest to understand this feature with a few examples:\n\npackage Example;\n\nuse Moose;\n\nsub foo {\nprint \"    foo\\n\";\n}\n\nbefore 'foo' => sub { print \"about to call foo\\n\"; };\nafter 'foo'  => sub { print \"just called foo\\n\"; };\n\naround 'foo' => sub {\nmy $orig = shift;\nmy $self = shift;\n\nprint \"  I'm around foo\\n\";\n\n$self->$orig(@);\n\nprint \"  I'm still around foo\\n\";\n};\n\nNow if I call \"Example->new->foo\" I'll get the following output:\n\nabout to call foo\nI'm around foo\nfoo\nI'm still around foo\njust called foo\n\nYou probably could have figured that out from the names \"before\", \"after\", and \"around\".\n\nAlso, as you can see, the before modifiers come before around modifiers, and after modifiers\ncome last.\n\nWhen there are multiple modifiers of the same type, the before and around modifiers run from the\nlast added to the first, and after modifiers run from first added to last:\n\nbefore 2\nbefore 1\naround 2\naround 1\nprimary\naround 1\naround 2\nafter 1\nafter 2\n\nWHY USE THEM?\nMethod modifiers have many uses. They are often used in roles to alter the behavior of methods\nin the classes that consume the role. See Moose::Manual::Roles for more information about roles.\n\nSince modifiers are mostly useful in roles, some of the examples below are a bit artificial.\nThey're intended to give you an idea of how modifiers work, but may not be the most natural\nusage.\n\nBEFORE, AFTER, AND AROUND\nMethod modifiers can be used to add behavior to methods without modifying the definition of\nthose methods.\n",
            "subsections": [
                {
                    "name": "Before and after Modifiers",
                    "content": "Method modifiers can be used to add behavior to a method that Moose generates for you, such as\nan attribute accessor:\n\nhas 'size' => ( is => 'rw' );\n\nbefore 'size' => sub {\nmy $self = shift;\n\nif (@) {\nCarp::cluck('Someone is setting size');\n}\n};\n\nAnother use for the before modifier would be to do some sort of prechecking on a method call.\nFor example:\n\nbefore 'size' => sub {\nmy $self = shift;\n\ndie 'Cannot set size while the person is growing'\nif @ && $self->isgrowing;\n};\n\nThis lets us implement logical checks that don't make sense as type constraints. In particular,\nthey're useful for defining logical rules about an object's state changes.\n\nSimilarly, an after modifier could be used for logging an action that was taken.\n\nNote that the return values of both before and after modifiers are ignored.\n"
                },
                {
                    "name": "Around modifiers",
                    "content": "An around modifier is more powerful than either a before or after modifier. It can modify the\narguments being passed to the original method, and you can even decide to simply not call the\noriginal method at all. You can also modify the return value with an around modifier.\n\nAn around modifier receives the original method as its first argument, *then* the object, and\nfinally any arguments passed to the method.\n\naround 'size' => sub {\nmy $orig = shift;\nmy $self = shift;\n\nreturn $self->$orig()\nunless @;\n\nmy $size = shift;\n$size = $size / 2\nif $self->likessmallthings();\n\nreturn $self->$orig($size);\n};\n"
                },
                {
                    "name": "Wrapping multiple methods at once",
                    "content": "\"before\", \"after\", and \"around\" can also modify multiple methods at once. The simplest example\nof this is passing them as a list:\n\nbefore [qw(foo bar baz)] => sub {\nwarn \"something is being called!\";\n};\n\nThis will add a \"before\" modifier to each of the \"foo\", \"bar\", and \"baz\" methods in the current\nclass, just as though a separate call to \"before\" was made for each of them. The list can be\npassed either as a bare list, or as an arrayref. Note that the name of the function being\nmodified isn't passed in in any way; this syntax is only intended for cases where the function\nbeing modified doesn't actually matter. If the function name does matter, use something like\nthis:\n\nfor my $func (qw(foo bar baz)) {\nbefore $func => sub {\nwarn \"$func was called!\";\n};\n}\n"
                },
                {
                    "name": "Using regular expressions to select methods to wrap",
                    "content": "In addition, you can specify a regular expression to indicate the methods to wrap, like so:\n\nafter qr/^command/ => sub {\nwarn \"got a command\";\n};\n\nThis will match the regular expression against each method name returned by \"getmethodlist\" in\nClass::MOP::Class, and add a modifier to each one that matches. The same caveats apply as above.\n\nUsing regular expressions to determine methods to wrap is quite a bit more powerful than the\nprevious alternatives, but it's also quite a bit more dangerous. Bear in mind that if your\nregular expression matches certain Perl and Moose reserved method names with a special meaning\nto Moose or Perl, such as \"meta\", \"new\", \"BUILD\", \"DESTROY\", \"AUTOLOAD\", etc, this could cause\nunintended (and hard to debug) problems and is best avoided.\n"
                },
                {
                    "name": "Execution order of method modifiers and inheritance",
                    "content": "When both a superclass and an inheriting class have the same method modifiers, the method\nmodifiers of the inheriting class are wrapped around the method modifiers of the superclass, as\nthe following example illustrates:\n\nHere is the parent class:\n\npackage Superclass;\nuse Moose;\nsub rant { printf \"        RANTING!\\n\" }\nbefore 'rant' => sub { printf \"    In %s before\\n\", PACKAGE };\nafter 'rant'  => sub { printf \"    In %s after\\n\",  PACKAGE };\naround 'rant' => sub {\nmy $orig = shift;\nmy $self = shift;\nprintf \"      In %s around before calling original\\n\", PACKAGE;\n$self->$orig;\nprintf \"      In %s around after calling original\\n\", PACKAGE;\n};\n1;\n\nAnd the child class:\n\npackage Subclass;\nuse Moose;\nextends 'Superclass';\nbefore 'rant' => sub { printf \"In %s before\\n\", PACKAGE };\nafter 'rant'  => sub { printf \"In %s after\\n\",  PACKAGE };\naround 'rant' => sub {\nmy $orig = shift;\nmy $self = shift;\nprintf \"  In %s around before calling original\\n\", PACKAGE;\n$self->$orig;\nprintf \"  In %s around after calling original\\n\", PACKAGE;\n};\n1;\n\nAnd here's the output when we call the wrapped method (\"Child->rant\"):\n\n% perl -MSubclass -e 'Subclass->new->rant'\n\nIn Subclass before\nIn Subclass around before calling original\nIn Superclass before\nIn Superclass around before calling original\nRANTING!\nIn Superclass around after calling original\nIn Superclass after\nIn Subclass around after calling original\nIn Subclass after\n"
                }
            ]
        },
        "INNER AND AUGMENT": {
            "content": "Augment and inner are two halves of the same feature. The augment modifier provides a sort of\ninverted subclassing. You provide part of the implementation in a superclass, and then document\nthat subclasses are expected to provide the rest.\n\nThe superclass calls \"inner()\", which then calls the \"augment\" modifier in the subclass:\n\npackage Document;\n\nuse Moose;\n\nsub asxml {\nmy $self = shift;\n\nmy $xml = \"<document>\\n\";\n$xml .= inner();\n$xml .= \"</document>\\n\";\n\nreturn $xml;\n}\n\nUsing \"inner()\" in this method makes it possible for one or more subclasses to then augment this\nmethod with their own specific implementation:\n\npackage Report;\n\nuse Moose;\n\nextends 'Document';\n\naugment 'asxml' => sub {\nmy $self = shift;\n\nmy $xml = \"  <report>\\n\";\n$xml .= inner();\n$xml .= \"  </report>\\n\";\n\nreturn $xml;\n};\n\nWhen we call \"asxml\" on a Report object, we get something like this:\n\n<document>\n<report>\n</report>\n</document>\n\nBut we also called \"inner()\" in \"Report\", so we can continue subclassing and adding more content\ninside the document:\n\npackage Report::IncomeAndExpenses;\n\nuse Moose;\n\nextends 'Report';\n\naugment 'asxml' => sub {\nmy $self = shift;\n\nmy $xml = '    <income>' . $self->income . '</income>';\n$xml .= \"\\n\";\n$xml .= '    <expenses>' . $self->expenses . '</expenses>';\n$xml .= \"\\n\";\n\n$xml .= inner() || q{};\n\nreturn $xml;\n};\n\nNow our report has some content:\n\n<document>\n<report>\n<income>$10</income>\n<expenses>$8</expenses>\n</report>\n</document>\n\nWhat makes this combination of \"augment\" and \"inner()\" special is that it allows us to have\nmethods which are called from parent (least specific) to child (most specific). This inverts the\nnormal inheritance pattern.\n\nNote that in \"Report::IncomeAndExpenses\" we call \"inner()\" again. If the object is an instance\nof \"Report::IncomeAndExpenses\" then this call is a no-op, and just returns false. It's a good\nidea to always call \"inner()\" to allow for future subclassing.\n",
            "subsections": []
        },
        "OVERRIDE AND SUPER": {
            "content": "Finally, Moose provides some simple sugar for Perl's built-in method overriding scheme. If you\nwant to override a method from a parent class, you can do this with \"override\":\n\npackage Employee;\n\nuse Moose;\n\nextends 'Person';\n\nhas 'jobtitle' => ( is => 'rw' );\n\noverride 'displayname' => sub {\nmy $self = shift;\n\nreturn super() . q{, } . $self->jobtitle();\n};\n\nThe call to \"super()\" is almost the same as calling \"$self->SUPER::displayname\". The difference\nis that the arguments passed to the superclass's method will always be the same as the ones\npassed to the method modifier, and cannot be changed.\n\nAll arguments passed to \"super()\" are ignored, as are any changes made to @ before \"super()\" is\ncalled.\n",
            "subsections": []
        },
        "SEMI-COLONS": {
            "content": "Because all of these method modifiers are implemented as Perl functions, you must always end the\nmodifier declaration with a semi-colon:\n\nafter 'foo' => sub { };\n",
            "subsections": []
        },
        "EXCEPTIONS AND STACK TRACES": {
            "content": "An exception thrown in a \"before\" modifier will prevent the method it modifies from being called\nat all. An exception in an \"around\" modifier may prevent the modified method from being called,\ndepending on how the \"around\" modifier is structured. An exception in an \"after\" modifier\nobviously cannot prevent the method it wraps from being called.\n\nBoth \"override\" and \"augment\" are similar to \"around\" in that they can decide whether or not to\ncall the method they modify before or after throwing an exception.\n\nFrom the caller's perspective, an exception in a method modifier will look like the method it\ncalled threw an exception. However, method modifiers are just standard Perl subroutines. This\nmeans that they end up on the stack in stack traces as an additional frame.\n",
            "subsections": []
        },
        "CAVEATS": {
            "content": "These method modification features do not work well with multiple inheritance, due to how method\nresolution is performed in Perl. Experiment with a test program to ensure your class hierarchy\nworks as expected, or more preferably, don't use multiple inheritance (roles can help with\nthis)!\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "*   Stevan Little <stevan@cpan.org>\n\n*   Dave Rolsky <autarch@urth.org>\n\n*   Jesse Luehrs <doy@cpan.org>\n\n*   Shawn M Moore <sartak@cpan.org>\n\n*   יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>\n\n*   Karen Etheridge <ether@cpan.org>\n\n*   Florian Ragwitz <rafl@debian.org>\n\n*   Hans Dieter Pearcey <hdp@cpan.org>\n\n*   Chris Prather <chris@prather.org>\n\n*   Matt S Trout <mstrout@cpan.org>\n",
            "subsections": []
        },
        "COPYRIGHT AND LICENSE": {
            "content": "This software is copyright (c) 2006 by Infinity Interactive, Inc.\n\nThis is free software; you can redistribute it and/or modify it under the same terms as the Perl\n5 programming language system itself.\n",
            "subsections": []
        }
    },
    "summary": "Moose::Manual::MethodModifiers - Moose's method modifiers",
    "flags": [],
    "examples": [],
    "see_also": []
}