我正在努力学习Moops,我无法掌握如何使用pop和迭代lexical_has arrayRefs。你能用代码证明他们的用法吗?
我写了以下内容:
lexical_has people => (is => 'rw',
isa => ArrayRef,
default => sub { [] },
accessor => \(my @people),
required => 0);
我试图填充它:
$self->$people[$counter](Employee->new()->dispatch());
但它一直让我感到错误"> $ people []"
附近的语法错误答案 0 :(得分:3)
您正在设置accessor => \@people
,这显示了对lexical_has
所做的基本误解。 lexical_has
将coderef安装到该变量中,因此它应该是标量。
因此,一旦$people
作为标量,lexical_has
已安装了coderef,则$self->$people()
或$self->$people
是一个返回arrayref的方法调用。因此@{ $self->$people }
是(非ref)数组本身,可以用于push / pop / shift / unshift / grep / map / sort / foreach / etc。
快速举例:
use Moops;
class GuestList {
lexical_has people => (
isa => ArrayRef,
default => sub { [] },
reader => \(my $people),
lazy => 1,
);
method add_person (Str $name) {
push @{ $self->$people }, $name;
}
method announce () {
say for @{ $self->$people };
}
}
my $list = GuestList->new;
$list->add_person("Alice");
$list->add_person("Bob");
$list->add_person("Carol");
$list->announce;
输出是:
Alice
Bob
Carol
以下是使用people
...
use Moops;
class GuestList {
has people => (
is => 'ro',
isa => ArrayRef,
default => sub { [] },
lazy => 1,
);
method add_person (Str $name) {
push @{ $self->people }, $name;
}
method announce () {
say for @{ $self->people };
}
}
my $list = GuestList->new;
$list->add_person("Alice");
$list->add_person("Bob");
$list->add_person("Carol");
$list->announce;