如何使用Mousse为数组属性添加便利函数?

时间:2011-04-28 10:07:20

标签: perl moose

这是一个基本问题,我担心。看看下面的代码。我想知道是否有办法声明slices属性,以避免使用get_slicesadd_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;

谢谢!

1 个答案:

答案 0 :(得分:10)

我是穆斯的初学者,但我认为你需要这个:

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