How can I implement a new handle like Moose?

Suppose I wanted to add say functionality to String (note that this is a simpler example than reality). Therefore i could

 has foo => ( isa => 'Str', traits => [ 'String' ], handles => { say_foo => 'say', } ); 

which of course I could use.

 $self->foo( 'bar' ); $self->say_foo; 

which will print literally

 'bar\n' 

I assume the subroutine will be something like this

 sub _say_attr { my ( $self, $attr ) = @_; say $attr; } 

Can someone help me fill in the gaps in how I could implement this? I really don't really understand the documentation on how to write my own handles .

I do not need to know how to change the features of String . Since I want to have a common handler, where I do not 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', } ); 

therefore, say here is probably an identifier for a function that does not need the hard-coded attribute name that calls it.

+4
source share
1 answer

Are you sure you want to add say to String or are you happy with adding say_foo to foo ?

The latter is easy:

 has foo => ( isa => 'Str', traits => [ 'String' ], handles => { say_foo => sub { say $_[0]->foo; }, } ); 

If you want a more general solution, you should look at Moose :: Meta :: Attribute :: Native :: Trait :: String and copy / wrap / subclass, and not try to change it.

+2
source

All Articles