Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can Perl Moose objects have directly an array/hash attribute?

Can be done something like this in Perl?

package Person;
use Moose;

has 'friends' => ( is => 'rw', isa => 'Array', default => () );

I see that perl compiler doesn't accept this particular syntax, but do I use wrong syntax, or it is not possible at all? Do I have to use an array reference instead?

I'm pretty new to perl so the question is maybe dumb and I somehow feel the answer would be "no", but I haven't found any mention about it.

Thanks in advance

like image 693
amik Avatar asked Mar 24 '26 11:03

amik


1 Answers

"List" has quite a few definitions. Presuming you mean an collection or ordered collection of Person objects, I'd use an array I'd pass to the accessor using a reference

has friends => (
   is      => 'rw',
   isa     => 'ArrayRef[Person]',
   default => sub { [] },
);

push @{ $o->friends }, $person;

for (@{ $o->friends }) {
   ...
}

You can add useful methods using Moose::Meta::Attribute::Native::Trait::Array.

has friends => (
   traits  => [qw( Array )],
   is      => 'rw',
   isa     => 'ArrayRef[Person]',
   default => sub { [] },
   handles => {
      push_friends => 'push',
   },
);

$o->push_friends($person);

for (@{ $o->friends }) {
   ...
}
like image 171
ikegami Avatar answered Mar 27 '26 12:03

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!