6

I am using Moose objects, but I need to declare static members for things that will be done just once and are not object related.

Do you have any ideas or examples?

Thanks

Dotan.

Svante
  • 50,694
  • 11
  • 78
  • 122
Dotan
  • 61
  • 2

3 Answers3

6

You can use MooseX::ClassAttribute:

package SomeClass;
use Moose;
use MooseX::ClassAttribute;

class_has 'static_member' => ( is => 'rw' );

The member is accesses using SomeClass->static_member.

bvr
  • 9,687
  • 22
  • 28
2

under all the cervine-ness there is still Plain Old Perl

so just set a variable in the class .pm file

package SomeClass;
use Moose;

my $instance_counter = 0;

around BUILDARGS => sub {
    $instance_counter += 1;
}

. . .
2

I tried playing around with MooseX::ClassAttribute as bvr suggested, but I ended up just setting them as read-only members with a default:

has 'static_thing' => ( is => 'ro', init_arg => undef, default => 42 );

It seems simpler.

friedo
  • 65,762
  • 16
  • 114
  • 184
  • 1
    For anything that doesn't consume a lot of memory, or where it is okay to have multiple copies of the same thing, this is fine -- but sometimes you need just one copy of the same thing (say a database handle) to be shared across all objects, which is where a class attribute can be of use. – Ether Mar 02 '11 at 17:03
  • I used that on one or two places so far, typically for something that needs to be shared among class members (as Ether said). – bvr Mar 02 '11 at 17:10
  • 1
    Also note that you'd need an instance to access the non-static attribute. Getting an instance is not always convenient. – Carl Mäsak Jun 15 '11 at 14:43