Is it possible to create an attribute that can only be set in the constructor in Moose?

Is it possible to create an attribute that can only be set in the constructor in Moose? I'd like to do something like this:

my $foo = new Foo(file => 'foo.txt');
my $bar = new Foo(string => $str);
$foo->file('baz.txt'); # dies

I know that I can create an attribute that cannot be set in the constructor, but the extra argument seems to be missing.

+3
source share
1 answer

Isn't this just a read-only attribute? If i write

package Foo;
use Moose;

has 'file' => (is => 'ro', isa => 'Str');
has 'string' => (is => 'rw', isa => 'Str');

1;

then your code dies with

Cannot assign a value to a read-only accessor
+9
source

Source: https://habr.com/ru/post/1714952/


All Articles