这是一个基本问题,我担心。看看下面的代码。我想知道是否有办法声明slices
属性,以避免使用get_slices
和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;
谢谢!
答案 0 :(得分:10)
我是穆斯的初学者,但我认为你需要这个:
has slices =>
is => 'rw',
isa => 'ArrayRef[Str]',
default => sub { [] },
traits => ['Array'],
handles => {
add_slice => 'push',
get_slices => 'elements',
},
;