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?
Others have given good answers for mesh/zip side of the question, but if you are just creating a hash from an array of keys and one of values you can do it with the under-appreciated hash slice.
#!/usr/bin/env perl
use strict;
use warnings;
my @keys = qw/abel baker charlie dog easy fox/;
my @values = qw/a b c d e f/;
my %hash;
@hash{@keys} = @values;
use Data::Dumper;
print Dumper \%hash;
Addendum
I got to thinking why one may choose one method over the other. I personally think that the slice implementation is as readable as the zip, but others may disagree. If you are doing this often, you may care about speed, in which case the slice form is faster.
#!/usr/bin/env perl
use strict;
use warnings;
use List::MoreUtils qw/zip/;
use Benchmark qw/cmpthese/;
my @keys = qw/abel baker charlie dog easy fox/;
my @values = qw/a b c d e f/;
cmpthese( 100000, {
zip => sub {
my %hash = zip @keys, @values;
},
slice => sub {
my %hash;
@hash{@keys} = @values;
},
});
results:
Rate zip slice
zip 51282/s -- -34%
slice 78125/s 52% --
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With