Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Perl/Moose, what happens to the value returned by modifiers?

Learning perl I just recently discovered the wonders of Moose!

I'm trying to wrap my head around modifiers -- or at least how the return values are handled... do they get stored someplace?

{package Util::Printable;

use Moose::Role;

  requires 'to_str','init';

  before 'to_str' => sub {
      my($self) = @_;
      $self->{to_string} = "my string thing";
      return $self->{to_string}; 
  };

  after 'init' => sub{
    my($self) = @_;
    $self->{roles} = __PACKAGE__;
    $self->{is_printable} = 1;
  };


}
1;
__END__ 

Using the Printable Role

{package MonkeyPrint;
use Moose;

with 'Util::Printable';


  sub init{
    my($self) = @_;
    return 1;
  };

  sub BUILD{
    my($self) = @_;
    $self->init();  
  }


  # ------------------------------------------------------------------------ # 
  # Printable Support
  # ------------------------------------------------------------------------ #
  use overload '""' => 'to_str';  

  sub to_str {
      my($self) = @_;
      $self->{to_string} = __PACKAGE__;
      return $self->{to_string}; 
  };


 __PACKAGE__->meta->make_immutable;
}
1;
__END__ 
like image 743
qodeninja Avatar asked Oct 14 '25 03:10

qodeninja


1 Answers

Say a method has a before and an after wrapper.

  1. The before code is called.
  2. Its return value is ignored/discarded.
  3. The original method is called.
  4. It's value is saved.
  5. The after code is called.
  6. Its return value is ignored/discarded.
  7. The saved value is returned.

Use around if you need to alter or replace the value returned by the original method.

like image 186
ikegami Avatar answered Oct 17 '25 16:10

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!