How to use Moose to add convenience functions for array attributes?

This is the main question, I'm afraid. Take a look at the following code. I would like to know if there is a way to declare the slices attribute in such a way as to avoid the get_slices and add_slice .

 package Gurke; use Moose; has slices => is => 'rw', isa => 'ArrayRef[Str]', default => sub { [] }; sub get_slices { return @{ $_[0]->slices } } sub add_slice { my( $self, $slice ) = @_; push @{ $self->slices }, $slice; return; } no Moose; __PACKAGE__->meta->make_immutable; package main; # now a small test for the above package use strict; use warnings; use Test::More; my $gu = Gurke->new; $gu->add_slice( 'eins' ); $gu->add_slice( 'zwei' ); $gu->add_slice( 'drei' ); my @sl = $gu->get_slices; is shift @sl, 'eins'; is shift @sl, 'zwei'; is shift @sl, 'drei'; done_testing; 

Thanks!

+7
source share
1 answer

I am a beginner newbie, but I think you need this:

 has slices => is => 'rw', isa => 'ArrayRef[Str]', default => sub { [] }, traits => ['Array'], handles => { add_slice => 'push', get_slices => 'elements', }, ; 
+10
source

All Articles