您在设置accessor => \@people
,该显示对lexical_has
的作用有根本性的误解。 lexical_has
安装一个coderef到该变量,所以它应该是一个标量。
所以,一旦你有$people
作为一个标量,这lexical_has
安装了CODEREF进入,然后$self->$people()
或$self->$people
是它返回一个数组引用一个方法调用。因此@{ $self->$people }
是(non-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;
尼斯编辑。现在我怀疑你可能会得到答案。 – 2014-12-03 17:36:13