nysus has asked for the wisdom of the Perl Monks concerning the following question:

I'm new to Moose and scratching my head why some code I have is not working properly. Here's the relevant code.

package EventRepository; use Moose; has 'future_existing_events' => ( is => 'rw', isa => 'HashRef', lazy => 1, default => sub { {} }, trigger => \&_get_future_events('existing_events'), ); sub _get_future_events { print Dumper(\@_); ... }

Dumper results in this:

$VAR1 = [ 'existing_events' ];

As you can see, the object is not in the Dumper output and so is not getting passed to the method. I'm not even sure why the trigger method is getting called because I am not setting the future_existing_events attribute anywhere in my code. Other tirggered methods in my code receive the object just fine.

$PM = "Perl Monk's";
$MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
$nysus = $PM . ' ' . $MCF;
Click here if you love Perl Monks

Replies are listed 'Best First'.
Re: Moose not passing object to triggered method
by Anonymous Monk on Mar 22, 2016 at 14:19 UTC

    When I try your code (with minor modifications so it'll compile) I get an exception from Moose: "Trigger must be a CODE ref on attribute".

    The reason is that trigger => \&_get_future_events('existing_events'), first calls sub _get_future_events with the single argument 'existing_events' (which is the Dumper output you're seeing), and then takes a reference to its return value, and assigns that to trigger.

    So you either need to write trigger => \&_get_future_events, to assign a reference to sub _get_future_events to trigger, or, if you really need to pass an extra argument to _get_future_events, you could do something like trigger => sub { _get_future_events(@_,'existing_events') },.

      Putting in the anonymous subroutine with sub {} for the trigger did the trick. Thanks!

      $PM = "Perl Monk's";
      $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
      $nysus = $PM . ' ' . $MCF;
      Click here if you love Perl Monks

Re: Moose not passing object to triggered method
by nysus (Parson) on Mar 22, 2016 at 14:15 UTC

    If I remove the existing_events argument from the code, the triggered method no longer gets called. So I think the passing in an argument is the problem. Is it possible to pass an argument to a triggered method?

    $PM = "Perl Monk's";
    $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate";
    $nysus = $PM . ' ' . $MCF;
    Click here if you love Perl Monks

      Is it possible to pass an argument to a triggered method?

      I'm not sure about Moose, but in general this is called Currying (or "partial application"). The simplest form in Perl is shown in the other reply, but a quick search shows several modules that claim to make this easier (disclaimer: I haven't used any of them).