2

我想我已经为 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 Attributes(不使用 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', 
               },

如果有办法做到这一点,那就太好了,但我担心我可能在某处误解了一些关于如何或为什么为非本地属性创建处理程序的内容。

想法?

4

1 回答 1

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 类具有方法,因此无需编写特征来提供方法。

于 2011-09-26T19:00:42.447 回答