Thank you for pointing my mistake in using a hash slice to interleave two lists, tye. Here's my second attempt at interleaving two lists. This time I use an array slice, and (hope this makes sense) calculates the offset position for the two arrays in the final interleaved array:

#!/usr/bin/perl -w use strict; use Data::Dumper qw(Dumper); my @keys = qw(a b c d e f g h i j); #is longer than my @values = qw(1 2 3 4 5); #this.. my @array = interleave(\@keys, \@values); print Dumper(\@array); #let's see what happens sub interleave { my $array1 = shift; my $array2 = shift; my(@even, @odd); push @even, $_ * 2 for 0..$#$array1; push @odd, $_ * 2 + 1 for 0..$#$array2; my @interleaved; @interleaved[@even, @odd] = (@$array1, @$array2); return wantarray ? @interleaved : \@interleaved; } __END__

If one of the arrays is longer than the other, it will still interleave them as if they are the same length. This behaviour is essential if the interleaved array ever gets copied to a hash, or you need the array elements to be in pairs.

The method that I used to calculate the offsets inside interleave() is the fastest I could find through benchmarking. If there is a faster/cleaner/better way, I would love to hear it.


In reply to Re: Interleave two arrays (using an array slice) by dkubb
in thread interleave two arrays by eg

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.