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

后端 未结 7 764
一向
一向 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:41

    I find the following solution straightforward and easy to read:

    @a = (1, 2, 3);
    @b = ('apple', 'orange', 'grape');
    @zipped = map {($a[$_], $b[$_])} (0 .. $#a);
    

    I believe it's also faster than solutions that create the array in a wrong order first and then use slice to reorder, or solutions that modify @a and @b.

提交回复
热议问题