Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for with multiple arrays

Tags:

perl

raku

In Scheme you can iterate over multiple lists in with for-each:

> (for-each (lambda (a b) (display (+ a b)) (newline)) '(10 20 30) '(1 2 3))
11
22
33
> 

I know that in Perl you can use for to iterate over a single list. What's a good way to iterate over multiple lists as in the Scheme example?

I'm interested in answers for Perl 5 or 6.

like image 905
dharmatech Avatar asked Jun 10 '11 00:06

dharmatech


2 Answers

In Perl 6, the Zip operator is the nicest choice. If you want to get both values (and not compute the sum directly), you can use it without the plus sign:

for (10, 11, 12) Z (1, 2, 3) -> $a, $b {
    say "$a and $b";
}
like image 164
moritz Avatar answered Sep 29 '22 11:09

moritz


In Perl 5 you can use the module List::MoreUtils. Either with pairwise or with the iterator returned by each_array (which can take more than two arrays to iterate through in parallel).

use 5.12.0;
use List::MoreUtils qw(pairwise each_array);

my @one = qw(a b c d e);
my @two = qw(q w e r t);

my @three = pairwise {"$a:$b"} @one, @two;

say join(" ", @three);

my $it = each_array(@one, @two);
while (my @elems = $it->()) {
    say "$elems[0] and $elems[1]";
}
like image 41
Alex Avatar answered Sep 29 '22 11:09

Alex