Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - built-in function to "zipper" together two arrays?

Tags:

arrays

merge

perl

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?

like image 952
Chap Avatar asked May 26 '13 02:05

Chap


1 Answers

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%    --
like image 57
Joel Berger Avatar answered Oct 13 '22 22:10

Joel Berger