使用 Perl/Moose,修饰符返回的值会发生什么情况?
学习perl 我最近才发现Moose的奇妙之处!
我正在尝试了解修饰符 - 或者至少如何处理返回值......它们是否存储在某个地方?
{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__
使用可打印角色
{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__
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__
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设一个方法有一个
before
和一个after
包装器。before
代码。after
代码。如果需要更改或替换原始方法返回的值,请使用
around
。Say a method has a
before
and anafter
wrapper.before
code is called.after
code is called.Use
around
if you need to alter or replace the value returned by the original method.