develooper Front page | perl.moose | Postings from August 2016

Re: Why to use Moose roles ever?

Thread Previous | Thread Next
From:
Kent Fredric
Date:
August 11, 2016 04:15
Subject:
Re: Why to use Moose roles ever?
Message ID:
CAATnKFB1aXvoeT9iHXt5269Anp+bS=KSqvv+RcFA7O6DVXT8Ug@mail.gmail.com
On 11 August 2016 at 15:43, Niall Young <niall@iinet.net.au> wrote:
> Not sure how your example applies here Karen, there is no foo() declared in
> MyClass only a foo method modifier, and MyRole's foo() doesn't appear to be
> executed from your output?


In the example she gave, the point was not to call MyRole's foo, only
to replace it. ( Because Roles prohibit replacement by default, its a
conflict that must be manually resolved )

Hence, "around foo"  wraps MyRole::foo and *creates*  MyClass::foo
without the conflict.

If one wants to call MyRole::foo in the new MyClass::foo, this is done:

    package MyClass;
    use Moose;
    with 'MyRole';
    around foo => sub {
       my ( $orig, $self, @args );
       return join q[, ],  'I came from the class', $self->$orig( @args );
    };


This would print

  "I came from the class, I came from the role"

Noting that:

"$orig" is the "wrapped" sub, MyRole::foo

That calling it is optional, and you can call it anywhere in the wrapper.

That you can intercept its return value, and modify its arguments
before calling.


-- 
Kent

KENTNL - https://metacpan.org/author/KENTNL

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About