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.
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";
}
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]";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With