Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Trouble coercing array elements

by docdurdee (Scribe)
on Jul 29, 2011 at 13:17 UTC ( #917469=note: print w/ replies, xml ) Need Help??

in reply to Trouble coercing array elements

Thanks ikegami! Playing around with your code helped me learn this cool stuff. I soon realized that I wanted to leave both ArrayRef and Objects alone. Starting from ikegami's code, I added this, cleaned it up (I hope) and am posting it here for reference. Perl rocks! Moose rocks!

{ package MyArray; use namespace::autoclean; use Moose; use Moose::Util::TypeConstraints; subtype 'ValueOrObject' => as 'Value|Object'; subtype 'Inside::MyArray::Ents' => as 'ArrayRef[Value]|Object'; coerce 'Inside::MyArray::Ents' => from 'Value' => via { return [ $_ ] }; my $level2_constraint = Moose::Util::TypeConstraints::find_type_constraint( 'Inside::MyArray::Ents'); subtype 'MyArray::Ents' => as 'ArrayRef[Inside::MyArray::Ents]'; coerce 'MyArray::Ents' => from 'ArrayRef[Inside::MyArray::Ents|ValueOrObject]' => via { [ map $level2_constraint->coerce($_), @$_ ] }; has 'myarray' => ( traits => ['Array'], is => 'rw', isa => 'MyArray::Ents', default => sub { [] }, handles => { push => 'push', pop => 'pop', get => 'get', set => 'set', elements => 'elements', count => 'count', }, coerce => 1, ); __PACKAGE__->meta->make_immutable; } use Modern::Perl; use Math::VectorReal; 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('dog'); print Dumper $a0; $a0->push('1.0'); print Dumper $a0; my $vec1 = vector(1,2,3); $a0->push($vec1); print Dumper $a0; my $vec3 = $a0->get(5); my $vec2 = $a0->pop; print Dumper $vec2; print Dumper $vec3; say $vec1-$vec2; 1;

Comment on Re: Trouble coercing array elements
Download Code

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2016-02-10 01:57 GMT
Find Nodes?
    Voting Booth?

    How many photographs, souvenirs, artworks, trophies or other decorative objects are displayed in your home?

    Results (330 votes), past polls