Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moose ArrayRef attribute returned as an Array

Tags:

oop

perl

moose

I have a Moose class with an attribute that is an ArrayRef (read-only) and is manipulated internally by the object. But when someone calls the accessor method I want it to return an Array (or list) not a reference. Not only would this cut down on the amount of dereferencing that the user of the class has to do, but it will mean they can't accidentally tamper with the same ref that my object is using.

So what's the best way to do this? Some sort of coercion?

like image 820
mpeters Avatar asked Dec 07 '09 18:12

mpeters


2 Answers

Use Moose::Meta::Attribute::Native::Trait::Array and delegation, e.g.

handles => { my_array => 'elements' }

(via doy on #moose)

auto_deref has the undesirable behavior of still returning a reference if you call the accessor in scalar context.

like image 182
hdp Avatar answered Oct 05 '22 17:10

hdp


While you can use auto-deref, Moose::Manual::BestPractices says that this isn't the best way to do it, and that you should instead consider using Moose::Meta::Attribute::Native to accomplish that functionality.

like image 33
Adam Bellaire Avatar answered Oct 05 '22 19:10

Adam Bellaire