3

It's cool that it's possible to add them in sub classes or mix them in in roles. My problem is that it seems method modifiers from the base class get deactivated when subclasses redefine the method itself (not the modifier). Maybe I'm understanding method modifiers wrong. Example:

use feature 'say';

package Foo;
use Moose;

has called => (is => 'rw', isa => 'Bool', default => 0);
sub call { 'Foo called' }
after call => sub { shift->called(1) };

my  $foo = Foo->new();
say $foo->called;   # 0
say $foo->call;     # Foo called
say $foo->called;   # 1

package Bar;
use Moose;
extends 'Foo';

sub call { 'Bar called' }

my  $bar = Bar->new();
say $bar->called;   # 0
say $bar->call;     # Bar called
say $bar->called;   # 0

I expected the last output to be 1 like with $foo. What am I doing wrong?

memowe
  • 2,656
  • 16
  • 25

2 Answers2

2

What happens is this

  • you define a Foo::call
  • you modify that with after
  • you define a Bar::call that doesn't call Foo::Call

The modifiers are not magical runtime things, but class-definition time things. To do what you try to do here you'd have to structure your code differently

Leon Timmermans
  • 30,029
  • 2
  • 61
  • 110
0

@RobEarl posted a link to a very similar question. The solution posted over there was to use augment and although it looks a bit strange and its use is controversial, it could solve my problem:

package Foo;
use Moose;

has called => (is => 'rw', isa => 'Bool', default => 0);
sub call { inner(); shift->called(1); 'Foo called' }

package Bar;
use Moose;
extends 'Foo';

augment call => sub { 'Bar called' };

my  $bar = Bar->new();
say $bar->called;   # 0
say $bar->call;     # Bar called
say $bar->called;   # 1
Community
  • 1
  • 1
memowe
  • 2,656
  • 16
  • 25