2

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__ 
qodeninja
  • 10,946
  • 30
  • 98
  • 152
  • 1
    Cosmetic note: you don't need braces around your `package` block. `package` means "all that comes after will be in such package." As you'll usually stick to a single package per file, there'll be no anbiguity. Note that since 5.14 you can also use a `package Util::Printable { contents }` syntax that's more in line with the other namespaced curly-bracket languages. Whether the new syntax will displace the current common practice is yet to observe. – JB. Sep 13 '11 at 21:43

1 Answers1

6

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518