How can I prevent Perl Moose attributes from being read only when a new one is called?

I would just like to declare a read-only attribute in Moose that cannot be initialized when new is called. Therefore, after declaring the following:

package SOD::KuuAnalyze::ProdId; use Moose; has 'users' => (isa => 'ArrayRef[Str]', is => "ro"); 1; 

I do not want the following to work:

 my $prodid = SOD::KuuAnalyze::ProdId->new(users => ["one", "two"]); 
+6
new-operator perl attributes moose
source share
2 answers

Use the init_arg attribute init_arg (see "Constructor Parameters" in 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; 
+13
source share

What about

 package SOD::KuuAnalyze::ProdId; use Moose; has 'users' => ( isa => 'ArrayRef[Str]', is => 'ro', init_arg => undef, default => sub { [ 'one', 'two' ] } ); 

Setting init_arg to undef seems necessary to prevent the attribute from being set from the constructor.

+4
source share

All Articles