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

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

    I believe the proper way to do this is to use natatime, from List::MoreUtils:

    from the docs:

    natatime BLOCK LIST

    Creates an array iterator, for looping over an array in chunks of $n items at a time. (n at a time, get it?). An example is probably a better explanation than I could give in words.

    Example:

     my @x = ('a' .. 'g');
     my $it = natatime 3, @x;
     while (my @vals = $it->())
     {
         print "@vals\n";
     }
    

    This prints

    a b c
    d e f
    g
    

    The implementation of List::MoreUtils::natatime:

    sub natatime ($@)
    {
        my $n = shift;
        my @list = @_;
    
        return sub
        {
            return splice @list, 0, $n;
        }
    }
    

提交回复
热议问题