我想在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"]);
答案 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
以禁止从构造函数设置属性。