Iterating over more than one array in parallel


In the last example I'd like to show a totally different case. What if you have two (or more) array you'd like to combine somehow? How can you go over the elements of two arrays in parallel?

examples/arrays/z.p6
#!/usr/bin/perl6
use v6;

my @chars   = <a b c>;
my @numbers = <1 2 3>;

for @chars Z @numbers -> $letter, $number {
	say "$letter $number";
}

Output:

examples/arrays/z.p6.out
a 1
b 2
c 3

The Z infix operator version of the zip function allows the parallel use of two lists. Or that of more:

examples/arrays/z_on_more.p6
#!/usr/bin/perl6
use v6;

my @operator  = <+ - *>;
my @left      = <1 2 3>;
my @right     = <7 8 9>;

for @left Z @operator Z @right -> $a, $o, $b {
	say "$a $o $b";
}

Output:

examples/arrays/z_on_more.p6.out
1 + 7
2 - 8
3 * 9

Copyright 2006, 2007, 2008, 2009, 2010 Gabor Szabo http://szabgab.com/ Index | TOC
If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed