Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: Moose Accessor Question

by rhesa (Vicar)
on Feb 06, 2009 at 23:17 UTC ( #742036=note: print w/replies, xml ) Need Help??

in reply to Moose Accessor Question

You're looking for MooseX::AttributeHelpers:
package Wibble; use Moose; use MooseX::AttributeHelpers; has 'thingies' => ( metaclass => 'Collection::Array', is => 'ro', isa => 'ArrayRef[Str]', default => sub { [] }, provides => { push => 'add_thingies', elements => 'list_thingies', }, );
This adds wrapper methods into your class to manipulate the underlying arrayref. I've given them sensible names too: add_thingies to push new elements to the end of the array, and list_thingies to return the list of values.

Now you can add additional items like so:

my $w = Wibble->new( thingies => [ 'this', 'that' ]); print join(", ",$w->list_thingies())."\n"; # prints "this, that" # here's the bit that we just made work $w->add_thingies('another'); print join(", ",$w->list_thingies())."\n"; # prints "this, that, another"
The specific methods you can provide for ArrayRef attributes are listed in MooseX::AttributeHelpers::MethodProvider::List and MooseX::AttributeHelpers::MethodProvider::Array.

I can also recommend the Moose::Manual. It's a nice overview of how Moose works, and describes some of the commonly used extensions.

Replies are listed 'Best First'.
Re^2: Moose Accessor Question
by pileofrogs (Priest) on Feb 06, 2009 at 23:38 UTC


    That's what I'm looking for! Thanks! I've been reading the manual, but I hadn't found that answer. Thanks again!

Re^2: Moose Accessor Question
by Anonymous Monk on Feb 07, 2009 at 04:33 UTC

    Having “been there, done that” very recently... let me toss-in what it took me a very long time to figure out. (For whatever it may be worth...)

    (1) The methods (like "add_thingies") are iautomagically created for you/i by Moose, and they are attached to the iobject/i. In effect, they serve to iconceal/i from any of the object's clients that the underlying data structure exists.

    (2) Sometimes it's overkill. Sometimes List::Util and so-forth just works best. Also, I've had my buttsky saved dozens of times now by Data::Util's instance() function... The very-nicest thing about Moose is, “it's still Perl.”

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://742036]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2020-10-01 15:53 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (15 votes). Check out past polls.