I want to merge two arrays of equal length into a single array by taking the first element from array A, the first element from array B; second element from A, second element from B, etc. The following program illustrates the algorithm:
# file zipper.pl
use strict;
use warnings;
use 5.010;
my @keys = qw/abel baker charlie dog easy fox/;
my @values = qw/a b c d e f/;
# ==> Is there a builtin function that is equivalent of zipper()? <==
#
my %hash = zipper( \@keys, \@values );
while ( my ( $k, $v ) = each %hash ) {
say "$k=$v";
}
# zipper(): Take two equal-length arrays and merge them (one from A, one from B,
# another from A, another from B, etc.) into a single array.
#
sub zipper {
my $k_ref = shift;
my $v_ref = shift;
die "Arrays must be equal length" if @$k_ref != @$v_ref;
my $i = 0;
return map { $k_ref->[ $i++ ], $_ } @$v_ref;
}
Output
$ ./zipper.pl
easy=e
dog=d
fox=f
charlie=c
baker=b
abel=a
I'm wondering if I've overlooked a builtin function in Perl that will do the equivalent of zipper(). It will be at the innermost loop of the program, and needs to run as fast as possible. If there's not a built-in or a CPAN module, can anyone improve upon my implementation?