tags:

views:

38

answers:

2

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?

+2  A: 

You can try something like this:

has 'call_counter' => (
    is     => 'ro',
    writer => '_set_call_counter',
);

is => 'ro' makes the attribute read only. Moose generates a getter. Your methods will use the getter for incrementing the value, like so:

sub called {
    my $self = shift;
    $self->_set_call_counter( $self->call_counter + 1 );
    ...
}

writer => '_set_call_counter' generates a setter named _set_call_counter. Moose does not support true private attributes. Outside code can, technically, call _set_call_counter. By convention, though, applications do not call methods beginning with an underscore.

Robert Wohlfarth
+3  A: 

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/

draegtun