Moose只读属性特征以及如何设置它们?

Eva*_*oll 3 perl moose

如何设置Moose只读属性特征?

package AttrTrait;
use Moose::Role;
has 'ext' => ( isa => 'Str', is => 'ro' );

package Class;
has 'foo' => ( isa => 'Str', is => 'ro', traits => [qw/AttrTrait/] );

package main;
my $c = Class->new( foo => 'ok' );
$c->meta->get_attribute('foo')->ext('die') # ro attr trait
Run Code Online (Sandbox Code Playgroud)

如果您不能在构造函数或运行时设置它,那么Read Only属性特征的目的是什么?在Moose :: Meta :: Attribute中有什么我想念的吗?有没有办法设置它meta

$c->meta->get_attr('ext')->set_value('foo') # doesn't work either (attribute trait provided not class provided method)
Run Code Online (Sandbox Code Playgroud)

小智 6

您可以在构造函数中设置它:

package Class;
has 'foo' => ( isa => 'Str', is => 'ro', ext => 'whatever', traits => ['AttrTrait'] );
Run Code Online (Sandbox Code Playgroud)

您只需将它传递给正确的构造函数(属性的构造函数).