in reply to (tye)Re2: interleave two arrays
in thread interleave two arrays

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.