Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare/use static members in Moose?

Tags:

oop

perl

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.

like image 229
Dotan Avatar asked Mar 02 '11 14:03

Dotan


3 Answers

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.

like image 113
bvr Avatar answered Sep 20 '22 17:09

bvr


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.

like image 22
friedo Avatar answered Sep 20 '22 17:09

friedo


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

. . .
like image 28
user2631899 Avatar answered Sep 18 '22 17:09

user2631899