in reply to interleave two arrays

This uses a hash slice to achieve the same outcome:

#!/usr/bin/perl -w use strict; my @keys = qw(a b c d); my @values = qw(1 2 3 4); print interleave(\@keys, \@values); sub interleave { my %interleaved; @interleaved{ @{$_[0]} } = @{$_[1]}; return %interleaved; }

Replies are listed 'Best First'.
(tye)Re2: interleave two arrays
by tye (Sage) on Feb 03, 2001 at 20:41 UTC

    That only works if you consider "interleaving" to mean "throw away any pairs where the first array has duplicate values" and "sort the merged pairs in a pseudo-random order". (:

            - tye (but my friends call me "Tye")

      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.