Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is there a well-know equivalent of python's zip in perl?

I can write my own,

sub zip { my @A; foreach my $i (0..$#{$_[0]}) { push @A, [ map { $_->[$i] } @_ ]; } wantarray and return @A; return \@A; }

But it seems kinda clunky -- are there ready-made solutions? Also, I would like to unzip, as well as convert interleaved arrays into arrays of pairs, e.g., A1, B1, A2, B2 -pairs-> [ A1, B1, A2,B2 ]. Please tell me I simply need to RTFM!

Replies are listed 'Best First'.
Re: equivalent of python's zip in perl
by LanX (Saint) on Nov 21, 2010 at 22:24 UTC
    > Is there a well-know equivalent of python's zip in perl?

    see zip and other functions in List::MoreUtils and please use <code> tags.

    Cheers Rolf

      Eh, you ask Perl monks about python, you can't be surprised when they get the details wrong... To replicate the python zip's behavior:
      sub python_zip(\@\@;\@\@\@) { # Add more \@ to taste my $short = min(map(scalar(@$_), @_)); return &zip(map(@$_ == $short ? $_ : [@$_[0..$short-1]], @_)); }
Re: equivalent of python's zip in perl
by Corion (Patriarch) on Nov 21, 2010 at 22:26 UTC

    See List::Util::zip (or is it List::MoreUtils::zip ?).

    For converting interleaved arrays, there is natatime in the same module.

    Update: s/Scalar/List/g, spotted by LanX

Re: equivalent of python's zip in perl
by cdarke (Prior) on Nov 22, 2010 at 08:13 UTC
    ...and, there is a zip built-in function in Perl 6, for example:
    for zip(@names, @files, @cats) -> $name, $file, $cat {…}


    (Wow, I got the Perl 6 reply in before moritz!)
      There's also an infix Z operator (which is implemented in Rakudo, but works only with two lists at the moment):
      my %h = <a b c d e f g> Z (1, 2 ... *); # or as a meta operator: # infix ~ is string concatenation my @list = <a b c d> Z~ (1, 2 ... *); # @list is now ('a1', 'b2', 'c3', 'd4')