How do I read two items at a time in a Perl foreach loop?

前端 未结 19 1712
你的背包
你的背包 2020-12-14 15:12

What I\'m looking for is something like:

@list = qw(1 2 3 4 5 6);
foreach (@list) {
  #perl magic goes here 
  print \"i: $i, j:$j\\n\";
}

19条回答
  •  被撕碎了的回忆
    2020-12-14 15:22

    Risking the necromancy tag, I decided to add one more from Tim Toady's backpack:

    for (0 .. $#list) {
        next if $_ % 2;
        my ($i, $j) = @list[$_, $_ + 1];
        say "i:$i, j:$j";
    }
    

    Nondestructive, no duplicate lists, no state variables and reasonably terse.

提交回复
热议问题