我担心这是一个基本问题。看看下面的代码。我想知道是否有一种方法可以声明 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;
谢谢!
最佳答案
我是 Moose 初学者,但我认为你需要这个:
has slices =>
is => 'rw',
isa => 'ArrayRef[Str]',
default => sub { [] },
traits => ['Array'],
handles => {
add_slice => 'push',
get_slices => 'elements',
},
;
关于perl - 如何使用Moose为数组属性添加便捷功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5816927/