如何防止在调用new时设置Perl Moose只读属性?

时间:2009-11-28 22:59:10

标签: perl attributes new-operator moose

我想在Moose中声明一个只读属性,在调用new时无法初始化。因此,在宣布以下内容之后:

package SOD::KuuAnalyze::ProdId;

use Moose;

has 'users' => (isa => 'ArrayRef[Str]', is => "ro");

1;

我不希望以下工作:

my $prodid = SOD::KuuAnalyze::ProdId->new(users => ["one", "two"]);

2 个答案:

答案 0 :(得分:13)

使用init_arg属性配置(请参阅Moose::Manual::Attributes中的“构造函数参数”):

package SOD::KuuAnalyze::ProdId;
use Moose;

has 'users' => (
    isa => 'ArrayRef[Str]', is => "ro",
    init_arg => undef,    # do not allow in constructor
);
1;

答案 1 :(得分:4)

怎么样

package SOD::KuuAnalyze::ProdId;

use Moose;

has 'users' => ( isa => 'ArrayRef[Str]', is => 'ro', init_arg => undef, default => sub { [ 'one', 'two' ] } );

似乎有必要将init_arg设置为undef以禁止从构造函数设置属性。