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

Viewed 6347

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?

5 Answers

Alan W. Smith provided a private class variable with a lexical variable, but it is shared by all objects in the class. Try adding a new object to the end of the example script:

my $c1 = CountingObject->new();
printf( "%s\n", $c1->get_count() );
#  also shows a count of 10, same as $co

Using MooseX:Privacy is a good answer, though if you can't, you can borrow a trick from the inside-out object camp:

package CountingObject;

use Moose;

my %cntr;

sub BUILD { my $self = shift; $cntr{$self} = 0 }

sub add_one { my $self = shift; $cntr{$self}++; }

sub get_count { my $self = shift; return $cntr{$self}; }

1;

With that, each object's counter is stored as an entry in a lexical hash. The above can be implemented a little more tersely thus:

package CountingObject;

use Moose;

my %cntr;

sub add_one { $cntr{$_[0]}++ }

sub get_count { return $cntr{$_[0]}||0 }

1;
Related