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

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

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!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • 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
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            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?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others making s'mores by the fire in the courtyard of the Monastery: (4)
    As of 2018-05-20 14:40 GMT
    Find Nodes?
      Voting Booth?