Perl 6 has an operator Z, named zip, to interleave elements of two or more arrays.
my @a = 1,2 Z -1,-2; # (1,-1),(2,-2)
The zip is one of the list generating operators that gives the language some flavor of functional programming. This gets further as the usual semantics for lists is to get lazy generation, which means easy/efficient handling of large lists (and also the extreme case of infinite lists).
With zip, parallel iteration over multiple arrays becomes a piece of cake. No need for index variables and explicit indexing. For example, to compare two arrays, this code could work.
sub eq_array ( @array1, @array2 ) {
for @array1 Z @array2 -> $x, $y {
return False if $x !eqv $y;
}
return True;
}
The operator has a synonym counterpart as the zip function.
my @Z = 1..10;
# import &num2en from Perl 5 Lingua::EN::Numbers module
use :from< perl5 Lingua::EN::Numbers > < num2en >;
my @E = map { num2en($_) }, @Z;
for zip(@Z; @E) -> $num, $en {
say "$num is spelled $en";
}
# will print:
# 1 is spelled 'one'
# 2 is spelled 'two' ...
The default behavior is to read to the end of the shortest list. So to automatically check the match between a list of optional arguments and their expected types, the following code could help
my @sig = ( ::Int, ::Str, ::List, ::Set );
if @args.elems > @sig.elems {
die "too many arguments";
}
for @args Z @sig -> $arg, $type {
if $arg !~~ $type {
die "mismatch: $arg should be of type $type"
}
}
Thus, @args = ( 1, 'a', (1,2) ) will be alright. While @args = ( 1, 1, 1, 1, 1 ) will die due to excess of arguments and @args = ( 1, {}) will shout that a hash does not look like a string.
The next micro-article will appear tomorrow (September 19, 2007).
My thanks to the folks at #perl6 (at irc.freenode.net) and at the perl6-language@perl.org mailing list.
DISCLAIMERS
- These articles are not intented as a deep presentation of Perl 6 features, but only as a quick demonstration. If you want more, get involved.
- Some of the code here is unimplemented in current Perl 6 implementations.
LINKS
- “Traversing arrays in parallel” at Synopsis S03, the official source
- The introduction of this series
- Official Perl 6 Documentation
- Pugs, the pioneer Perl 6 implementation
- Perl 6 in your browser
- Parrot, the Perl 6 VM
$Revision: 1599 $


Very, very strange feature. In perl 5 I can use
use List::Util;
...
map [ $a[$_], $b[$_] ], 0..max(scalar @a, scalar @b)-1
for same result. On the other hand zipping is not so frequently operation... Very strange feature.
In Perl 5 you can use &zip from List::MoreUtils as well and the related iterators: &pairwise, &each_array, &each_arrayref. In Perl 6, the zip operator is enough to get all the behavior of these. You said the operation is not frequent, but I think it is so due to the lack of built-in support for it. Time will tell.