Well, having required something like this recently, I feel obliged to comment.

I particurly liked merlyn's solution:

@copy = @$r; while (my @pair = splice @copy, 0, 2) { push @$r2, [@pair]; }

However, I'll modify it slightly to show everyone what I came up with. (Maybe it's just me, but bit-wise operators always seem to pop-up in my code ... probably where they shouldn't :)

@copy = @$r; # I guess you know that your array will work for this, but # it may be desirable to check (especially for n-'tuples') # that the array is divisible by 2 (or n). I guess that # depending on what you're expecting this can be done on a # all or nothing basis, or inside the loop while (0..$#copy) { next if $_&1; # this skips all odds (you used a mod in # your original I think). To expand to more # 'tuples', you'd have to change this to # next if $_%n push @$r2, [$copy[$_],$copy[$_+1]]; }

In reply to Re: Processing arrays 2 elements at a time (TIMTOWTDI) by dimmesdale
in thread Processing arrays 2 elements at a time (TIMTOWTDI) by grinder

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!
  • 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, details, 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, summary, 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.