3

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 I can create an attribute that can not be set in constructor, but the complementary case seems to be missing.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
zoul
  • 102,279
  • 44
  • 260
  • 354
  • 3
    BTW, you should really not use the indirect method syntax (Foo->new is preferred to new Foo). See here for an explanation: http://stackoverflow.com/questions/429657/ – friedo Aug 12 '09 at 14:19

1 Answers1

9

Isn't that 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
oylenshpeegul
  • 3,404
  • 1
  • 18
  • 18