gpt4 book ai didi

arrays - Moose 阵列属性 : how do I use a set method?

转载 作者:行者123 更新时间:2023-12-01 15:03:33 25 4
gpt4 key购买 nike

我想定义一个数组作为类的属性,并在类实例化时用一些数据填充它。

我认为可以使用 $self->attribute->set($id, $value)方法以便在给定索引上设置元素。至少这是我从驼鹿身上了解到的documentation .

但是当我尝试

use Data::Dumper qw( Dumper );
use Moose;

has cells => (
is => 'rw',
traits => ['Array'],
isa => 'ArrayRef',
default => sub { [] },
);

my $app = __PACKAGE__->new();
$app->cells->set($_, $_) for 0..3;
print(Dumper($app->cells));

我得到
Can't call method "set" on unblessed reference

我该怎么做 set工作?

最佳答案

use Data::Dumper qw( Dumper );
use Moose;

has cells => (
is => 'rw',
traits => ['Array'],
isa => 'ArrayRef',
default => sub { [] },
handles => { # <---
set_cell => 'set', # <---
}, # <---
);

my $app = __PACKAGE__->new();
$app->set_cell($_, $_) for 0..3; # <---
print(Dumper($app->cells));

尽管评论中有相反的说法,但它在 BUILD 中运行良好也。
use Data::Dumper qw( Dumper );
use Moose;

has cells => (
is => 'rw',
traits => ['Array'],
isa => 'ArrayRef',
default => sub { [] },
handles => {
set_cell => 'set',
},
);

sub BUILD {
my ($self) = @_;
$self->set_cell($_, $_) for 0..3;
}

my $app = __PACKAGE__->new();
print(Dumper($app->cells));

关于arrays - Moose 阵列属性 : how do I use a set method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13896629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com