如何使用Moose为数组属性添加便捷功能?
我担心这是一个基本问题。看看下面的代码。我想知道是否有一种方法可以声明 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;
谢谢!
This is a basic question, I fear. Take a look at the following code. I'd like to know whether there is a way to declare the slices
attribute in such a way as to avoid the boilerplate of 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我是驼鹿初学者,但我认为你需要这个:
I'm a Moose beginner, but I think you need this: