lexical_has
의 기본적인 오해를 나타내는 accessor => \@people
을 설정하고 있습니다. lexical_has
은 코드 레터를 해당 변수에 설치하므로 스칼라가되어야합니다. 당신이 lexical_has
다음으로 코드 참조를 설치 한 스칼라로 $people
을 일단
그래서, $self->$people()
또는 $self->$people
은 arrayref를 반환하는 메소드 호출이다. 따라서 @{ $self->$people }
은 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
는
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;
니스 편집 ...
people
에 대한 대중의 속성을 사용하여 해당 코드입니다. 이제 나는 네가 대답을 할 수 있다고 생각한다. –