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

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

    This can be done non-destructively, with Eric Strom's simply fantastic List::Gen:

    perl -MList::Gen=":utility" -E '@nums = "1" .. "6" ; 
          say "i:$_->[0] j:$_->[1]" for every 2 => @nums'
    

    Output:

    i:1 j:2 
    i:3 j:4 
    i:5 j:6 
    

    Edit (add a CPAN-less version):

    Array slices and C-style for loop à la brian d foy and Tom Christiansen! This can be read as "use an index ($i) to loop through a @list foreach $n elements at a time":

    use v5.16; # for strict, warnings, say
    
    my @list = "1" .. "6";
    my $n = 2 ;   # the number to loop by
    $n-- ;        # subtract 1 because of zero index
    
    foreach (my $i = 0 ; $i < @list ; $i += $n ) { 
      say "i:", [ @list[$i..$i+$n] ]->[0], " j:", [ @list[$i..$i+$n] ]->[1];
      $i++ ;          
    }
    

    We access the results as elements (->[0]) of an anonymous array ([ ]). For more generic output the interpolated array slice could be used on its own, e.g.: print "@list[$i..$i+$n]"; changing the value of $n as required.

提交回复
热议问题