Instead of around ['do_something','do_otherthing'] => sub { ... }, try this, as suggested by Moose::Manual::MethodModifiers:

for my $method ('do_something','do_otherthing') { around $method => sub { my $orig = shift; my $self = shift; print "around $method\n"; if ($method eq 'do_something') { ... } $self->$orig(@_); }; }

Update 2: $orig and \&do_something are giving different code refs ... Could someone explain me why this happens?

By the time the piece of code "\&do_something" is executed, do_something is already pointing to the wrapped sub do_something.

{ package Bar; use Moose; sub do_something { print "did something\n" } my $before = \&do_something; around 'do_something' => sub { my $orig = shift; my $self = shift; print "around do_something\n"; print "\t\$orig=$orig\n"; print "\t\$before=$before\n"; print "\t\\&do_something=".\&do_something."\n"; }; } my $bar = Bar->new; $bar->do_something; print "can=", $bar->can('do_something'), "\n"; __END__ around do_something $orig=CODE(0x223d5e8) $before=CODE(0x223d5e8) \&do_something=CODE(0x228ae92) can=CODE(0x228ae92)

Update 3: A bit more explanation: Notice how $before holds the reference to the original sub do_something before it's wrapped by around, and ->can('do_something') reports the coderef of the final, wrapped method. Compare these two to $orig and \&do_something. Remember that the anonymous sub given to around doesn't get executed until the method is called, by which time it's already been wrapped, at which time \&do_something points to the wrapped method.

Update 1: In my very first code example, added an example of checking which method is being wrapped.


In reply to Re: Code ref inside around modifier (updated) by haukex
in thread Code ref inside around modifier by #perl_noob

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.