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

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

    As Mirod explains, there isn't much code to it. Here's pretty much all you would need. (Note that I don't have any checks for odd-numbered lists or the like.)

    #!/usr/bin/env perl
    use strict;
    use warnings;
    
    my @list = qw/1 2 3 4 5 6/;
    my $get_em = get_by(2, @list);
    
    while ( my ($i, $j) = $get_em->() ) {
      print "i: $i, j: $j\n";
    }
    
    sub get_by {
      my $n = shift;
      my @list = @_;
    
      return sub {
        return splice @list, 0, $n;
      }
    }
    

提交回复
热议问题