Dotan
Dotan

Reputation: 61

How can I declare/use static members in Moose?

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.

Upvotes: 6

Views: 1817

Answers (3)

Raja Guha-Mustafi
Raja Guha-Mustafi

Reputation: 41

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;
}

. . .

Upvotes: 2

friedo
friedo

Reputation: 67028

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.

Upvotes: 2

bvr
bvr

Reputation: 9697

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.

Upvotes: 6

Related Questions