Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

loops

perl

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"; } 

returns:

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

In response to a very good suggestion below, I need to specify that this script will run on someone else's build server, and I'm not allowed to use any modules from CPAN. Standard Perl only.

like image 964
Sean Cavanagh Avatar asked Feb 20 '09 14:02

Sean Cavanagh


People also ask

How does foreach loop work in Perl?

A foreach loop is used to iterate over a list and the variable holds the value of the elements of the list one at a time. It is majorly used when we have a set of data in a list and we want to iterate over the elements of the list instead of iterating over its range.

What is the difference between for loop and for each loop in Perl?

There is no difference. From perldoc perlsyn: The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity.

How do I iterate in Perl?

In each iteration, you can process each element of the list separately. This is why the for loop statement is sometimes referred to as foreach loop. In Perl, the for and foreach loop are interchangeable, therefore, you can use the foreach keyword in where you use the for keyword.


1 Answers

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;     } } 
like image 144
mirod Avatar answered Sep 29 '22 11:09

mirod