Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
go ahead... be a heretic
 
PerlMonks  

Comment on

( #3333=superdoc: print w/ replies, xml ) Need Help??

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;

In reply to Trouble coercing array elements by docdurdee

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others wandering the Monastery: (6)
    As of 2014-04-16 04:37 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      April first is:







      Results (413 votes), past polls