Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a Moose attribute "write once"?

Tags:

perl

moose

I would like to have a non-required Moose attribute that can be set only once.

If I use is => 'ro' I must set the attribute upon creation of the object, but I want to be able to add it afterwards (as long as it's not been set already).

like image 513
David B Avatar asked Nov 12 '10 13:11

David B


2 Answers

MooseX::SetOnce

like image 170
daxim Avatar answered Nov 16 '22 23:11

daxim


Use a method modifier:

has 'attr' => (
    is => 'rw',
    predicate => 'is_set',
    ...
};   

before 'attr' => sub {
     my $self = shift;
     die 'attr already set' if $self->is_set;
};
like image 5
Pedro Silva Avatar answered Nov 16 '22 22:11

Pedro Silva