in reply to Moose object construction

Instead of $self->visitors=$rules->{navigation}->{visitors}; have you tried $self->visitors($rules->{navigation}->{visitors}); ? Moose doesn't go as far as making the accessors into lvalue subs.

Replies are listed 'Best First'.
Re^2: Moose object construction
by saintex (Scribe) on Feb 10, 2011 at 09:06 UTC
    Hello, just tried:
    $self->visitors($rules->{navigation}->{visitors});
    but I have:
    Cannot assign a value to a read-only accessor at ...
    So that doesn't work.

      What you want to do is change your visitor attribute to be something like:

      has 'visitors' => ( is => 'ro', writer => '_set_visitors', init_arg => undef, );
      Then inside your BUILD method, you will want to do:
      $self->_set_visitors( ... );
      The init_arg being set to "undef" will ensure that no one can do:
      MyClass->new( visitors => ... )
      But all this said, you should really spend some time reading the Moose::Manual. Several of the mistakes you have made seem to be caused by the fact you are guessing and/or making assumptions of your own about how Moose works, rather then actually taking the time to learn how it actually works. You also might find some of the presentations on http://moose.perl.org helpful as well, there are several excellent introductory ones from recent conferences.

      You really too should give a look to MooseX::SimpleConfig as it solves this problem for you and the code has been battle tested already.

      -stvn
        Thanks for this. I wasn't aware that you could have a writer defined for a ro attribute. It still seems wrong to me that a writer should exist, and work, on a ro attribute, but it does solve the problem.

      Sorry about that. You can work around that somewhat by making the attribute rw, but with an internal writer, say _set_visitors(), so you can set the visitors attribute from within your code, but visitors() can't be used to set it.

      It's not perfect, but the only way around it that I can see would be to dynamically make the attribute rw, set the value and then make it ro, which isn't pretty. I'm assuming that can be done, though I've never tried.