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

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


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 perluse 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 perluse 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 slicezip   51282/s    --  -34%slice 78125/s   52%    --


Since you offered a CPAN idea, there is List::MoreUtils and zip.

use List::MoreUtils qw(zip);my @keys   = qw/abel baker charlie dog easy fox/;my @values = qw/a b c d e f/;my @zipped = zip @keys, @values;

The contents of @zipped would be:

abel, a, baker, b, charlie, c, dog, d, easy, e, fox, f

The nice part about using this method is you can zip more than two lists if you wish. Since Perl has no concept of a tuple type, it is almost like a flattening operation.


Although this specific function already exists in List::MoreUtils, you can use prototypes to give your own array functions the appearance of built-in array operators (like push, shift, pop):

sub zipper (++) {  # perldoc perlsub  my ($k, $v) = @_;  die "Arrays must be equal length" if @$k != @$v;  my $i;  return map { $k->[$i++], $_ } @$v}%hash = zipper @keys, @values;%hash = zipper \@keys, \@values;%hash = zipper $key_aref, $value_aref;