开发者

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

开发者 https://www.devze.com 2023-04-05 04:05 出处:网络
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?

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 'i开发者_运维问答nit' => 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__ 


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号