有人可以解释如何在Moops中实现和使用私有范围的数组?

时间:2014-12-03 16:59:14

标签: perl moose moops

我正在努力学习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 []"

附近的语法错误

1 个答案:

答案 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;