Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Processing arrays 2 elements at a time (TIMTOWTDI)

by dimmesdale (Friar)
on Aug 02, 2002 at 15:44 UTC ( [id://187130] : note . print w/replies, xml ) Need Help??

in reply to Processing arrays 2 elements at a time (TIMTOWTDI)

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]]; }