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

Re: Why to use Moose roles ever?

Thread Previous | Thread Next
Kent Fredric
August 11, 2016 04:15
Re: Why to use Moose roles ever?
Message ID:
On 11 August 2016 at 15:43, Niall Young <> 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.



Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About