Search code examples
perlmoose

How can I create internal (private) Moose object variables (attributes)?


I would like some attributes (perhaps this is the wrong term in this context) to be private, that is, only internal for the object use - can't be read or written from the outside.

For example, think of some internal variable that counts the number of times any of a set of methods was called.

Where and how should I define such a variable?


Solution

  • The Moose::Manual::Attributes shows the following way to create private attributes:

    has '_genetic_code' => (
       is       => 'ro',
       lazy     => 1,
       builder  => '_build_genetic_code',
       init_arg => undef,
    );
    

    Setting init_arg means this attribute cannot be set at the constructor. Make it a rw or add writer if you need to update it.

    /I3az/