如何在 Perl/Moose 中为对象的方法创建属性处理程序
我想我已经为 perl Natives 提供了属性处理程序!
package tree;
has '_branches' => (
traits => ['Hash'],
is => 'rw',
isa => 'HashRef[Any]',
handles => {
_set_branch => 'set',
_is_branch => 'defined',
_list_branches => 'keys',
_branch => 'get'
},
trigger => sub {
my($self,$hash) = @_;
$self->_build_branch($hash);
}
);
sub _build_branch{
my($self,$hash);
# do stuff!
#return altered or coerced hash
return $hash;
}
你觉得怎么样?
但是,假设我有一个具有以下方法的 LinkedList 对象,
LinkedList{}
LinkedList.append()
LinkedList.insert()
LinkedList.size()
LinkedList.has_children()
LinkedList.remove()
LinkedList.split()
有没有一种方法可以通过 Moose 属性(不使用 MooseX)处理该对象的方法 - 与此类似?
package Bucket;
has '_linkedlist' => (
traits => ['LinkedList'],
is => 'rw',
isa => 'LinkedListRef[Any]',
handles => {
_add_link => 'append',
_insert_link => 'insert',
_count_links => 'size',
_del_link => 'remove',
_split_at_link => 'split',
_has_sublinks => 'has_children',
},
如果有一种方法可以做到这一点,那就太好了,但我担心我可能在某些地方误解了如何或为何为非本机属性创建处理程序。
想法?
I think I've got attribute handlers down for perl Natives!
package tree;
has '_branches' => (
traits => ['Hash'],
is => 'rw',
isa => 'HashRef[Any]',
handles => {
_set_branch => 'set',
_is_branch => 'defined',
_list_branches => 'keys',
_branch => 'get'
},
trigger => sub {
my($self,$hash) = @_;
$self->_build_branch($hash);
}
);
sub _build_branch{
my($self,$hash);
# do stuff!
#return altered or coerced hash
return $hash;
}
What do you think?
But let's say for example I have a LinkedList object with the following methods
LinkedList{}
LinkedList.append()
LinkedList.insert()
LinkedList.size()
LinkedList.has_children()
LinkedList.remove()
LinkedList.split()
Is there a way handle the object's methods via Moose Attributes (without using MooseX) - similar to this?
package Bucket;
has '_linkedlist' => (
traits => ['LinkedList'],
is => 'rw',
isa => 'LinkedListRef[Any]',
handles => {
_add_link => 'append',
_insert_link => 'insert',
_count_links => 'size',
_del_link => 'remove',
_split_at_link => 'split',
_has_sublinks => 'has_children',
},
It would be great if there was a way to do this, but I'm concerned maybe I've misunderstood something somewhere about how or why to create handlers for non-native attributes.
Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你只是让事情变得过于复杂,还是我错过了什么?
哈希没有方法,这就是它涉及特征的原因。该特质添加了方法。您的 LinkedList 类具有方法,因此无需编写特征来提供方法。
Are you simply overcomplicating things, or am I missing something?
Hashes don't have methods, which is why it involves a trait. The trait adds the methods. Your LinkedList class has methods, so no need to write a trait to provide the methods.