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.
- The
before
code is called. - Its return value is ignored/discarded.
- The original method is called.
- It's value is saved.
- The
after
code is called. - Its return value is ignored/discarded.
- The saved value is returned.
Use around
if you need to alter or replace the value returned by the original method.
精彩评论