3

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?

qodeninja
  • 10,946
  • 30
  • 98
  • 152
  • Is there a reason why you want a linked list trait (is it for learning purposes)? The reason I say this is because the `ArrayRef` type with the `Array` trait can handle everything you want there (except for split). Internally, perl arrays are linked lists anyway. But your class doesn't particularly need to know that. – stevenl Sep 27 '11 at 08:58
  • Yeah it was just a learning exercise -- I used LinkedList as a simple example to understand what was happening with Moose attributes – qodeninja Oct 14 '11 at 16:48

1 Answers1

5

Are you simply overcomplicating things, or am I missing something?

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', 
   },
);

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518