我认为我已经为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',
},
如果有办法做到这一点会很棒,但我担心的是我可能会误解某些地方有关如何或为何为非原生属性创建处理程序。
思想?
答案 0 :(得分:4)
你只是简单地过度复杂,或者我错过了什么?
package Bucket;
has '_linkedlist' => (
is => 'rw',
isa => 'LinkedList',
handles => {
_add_link => 'append',
_insert_link => 'insert',
_count_links => 'size',
_del_link => 'remove',
_split_at_link => 'split',
_has_sublinks => 'has_children',
},
);
哈希没有方法,这就是它涉及特征的原因。特征添加了方法。您的LinkedList类有方法,因此无需编写特征来提供方法。