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

前端 未结 19 1631
你的背包
你的背包 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:16

    another approach, not fully clean, but usable. each creates iterator, you can use it twice. when parameter is classic array, it returns index and value, please read this: https://perldoc.perl.org/functions/each.html

    so, your code can be like this:

    my @array=qw(one two three four five); #five element as unpaired will be ignored
    while (my ($i1,$one,$i2,$two)=(each(@array),each(@array)) {
      #we will use $ix for detect end of array
      next unless defined $i1 and defined $i2; #secure complete end of array
      print "fetched array elements: $one => $two\n";
    };
    

    Example above will not destruct source data, against shift or similar. I hope this we helpful for anyone. of course case with plain iterator is much better.

提交回复
热议问题