如何为 Moose 类型特征实现新句柄?
假设我想将 say
功能添加到 String
(注意:这是一个比现实更简单的示例)。所以我可以拥有
has foo => (
isa => 'Str',
traits => [ 'String' ],
handles => {
say_foo => 'say',
}
);
我当然可以用来做的事情。
$self->foo( 'bar' );
$self->say_foo;
这会从字面上打印
'bar\n'
我想象子例程会是这样的
sub _say_attr {
my ( $self, $attr ) = @_;
say $attr;
}
任何人都可以帮助我填补我如何实际实现这个的空白吗?我并没有真正看到太多关于如何编写自己的句柄
的文档。
我真的不需要知道如何修改 String
特征。尽管我希望能够拥有一个通用处理程序,但我不需要知道当前属性的名称即可使其工作。
has foo => (
isa => 'Str',
traits => [ 'PrintString' ],
handles => {
say_foo => 'say',
}
);
has bar => (
isa => 'Str',
traits => [ 'PrintString' ],
handles => {
say_bar => 'say',
}
);
所以 say
这里可能是一个函数的标识符,该函数不需要调用它的属性的硬编码名称。
Lets's say I wanted to add say
functionality to String
( note: this is a more simple example than reality ). So I could have
has foo => (
isa => 'Str',
traits => [ 'String' ],
handles => {
say_foo => 'say',
}
);
which I then of course would be able to use to do.
$self->foo( 'bar' );
$self->say_foo;
which would print literally
'bar\n'
I imagine the subroutine would be something like this
sub _say_attr {
my ( $self, $attr ) = @_;
say $attr;
}
Can anyone help me fill in the gaps on how I might actually implement this? I don't really see much in the way of documentation on how to write your own handles
.
I don't really need to know how to modify the String
traits. So much as I want to be able to have a generic handler, where I don't need to know the name of the current attribute in order to make it work.
has foo => (
isa => 'Str',
traits => [ 'PrintString' ],
handles => {
say_foo => 'say',
}
);
has bar => (
isa => 'Str',
traits => [ 'PrintString' ],
handles => {
say_bar => 'say',
}
);
so say
here is probably an identifier for a function which does not need a hardcoded name of an attribute which is calling it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您真的想将
say
添加到String
中,还是满足于将say_foo
添加到foo
中?后者很简单:
如果您想要更通用的解决方案,您应该查看 Moose::Meta::Attribute::Native::Trait::String 并复制/包装/子类化它而不是试图改变它。
Do you really want to add
say
toString
, or would you be content with addingsay_foo
tofoo
?The latter is easy:
If you wanted to a more general solution, You should look at Moose::Meta::Attribute::Native::Trait::String and copy/wrap/subclass it rather than trying to change it.