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

后端 未结 7 762
一向
一向 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条回答
  •  -上瘾入骨i
    2020-12-02 16:24

    my @l1 = qw/1 2 3/;
    my @l2 = qw/7 8 9/;
    my @out; 
    push @out, shift @l1, shift @l2 while ( @l1 || @l2 );
    

    If the lists are a different length, this will put 'undef' in the extra slots but you can easily remedy this if you don't wish to do this. Something like ( @l1[0] && shift @l1 ) would do it.

    Hope this helps!

提交回复
热议问题