docdurdee has asked for the wisdom of the Perl Monks concerning the following question:
My second post today! inspired by the first. I would like to set up an attribute that is an array of arrayrefs with coercion of nonarrayrefs to array refs. eg.
[ 0, [ 0, 0, 0 ], [1,2,3] ] into [ [0], [ 0, 0, 0 ], [1,2,3] ]also, I'd like to be able to push or set elements to the AoA with coercion as well. Here is my attempt:
{ package MyArray; use namespace::autoclean; use Moose::Util::TypeConstraints; use Moose; subtype 'myarray' => as 'ArrayRef[Num|Str|Int]'; coerce 'myarray' => from 'Num|Str|Int' => via {[$_]}; has 'myarray' => ( traits => ['Array'], is => 'rw', isa => 'myarray', default => sub { [] }, handles => { push => 'push', get => 'get', set => 'set', elements => 'elements', count => 'count', }, coerce => 1, ); __PACKAGE__->meta->make_immutable; } use Modern::Perl; my $a0 = MyArray->new( myarray => [ 0, [ 0, 0, 0 ], [1,2,3] ] ) ; use Data::Dumper; print Dumper $a0; $a0->set(1,'cat'); print Dumper $a0; $a0->push(2.0); print Dumper $a0;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Trouble coercing array elements
by ikegami (Patriarch) on Jul 28, 2011 at 21:46 UTC | |
Re: Trouble coercing array elements
by docdurdee (Scribe) on Jul 29, 2011 at 13:17 UTC |
Back to
Seekers of Perl Wisdom