Is there an elegant zip to interleave two lists in Perl 5?

后端 未结 7 765
一向
一向 2020-12-02 15:45

I recently \"needed\" a zip function in Perl 5 (while I was thinking about How do I calculate relative time?), i.e. a function that takes two lists and \"zips\" them togethe

7条回答
  •  一整个雨季
    2020-12-02 16:31

    The List::MoreUtils module has a zip/mesh function that should do the trick:

    use List::MoreUtils qw(zip);
    
    my @numbers = (1, 2, 3);
    my @fruit = ('apple', 'orange', 'grape');
    
    my @zipped = zip @numbers, @fruit;
    

    Here is the source of the mesh function:

    sub mesh (\@\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@) {
        my $max = -1;
        $max < $#$_  &&  ($max = $#$_)  for @_;
    
        map { my $ix = $_; map $_->[$ix], @_; } 0..$max; 
    }
    

提交回复
热议问题