On Friday, July 20, Ilya Sterin wrote:
>No, I don't think you are understanding it correctly. It's not about
>looping sequentially, but rather simultaneouly, for comparison purposes.
>
>@foo = (1,2,3);
>@bar = (1,2,3);
>for my ($foo, $bar) (@foo, @bar) #As the index for @foo increases, so
> #does @bar index
>{
>print "OK\n" if $foo == $bar;
>}
>
>Will print...
>OK
>OK
>OK
>
>Ilya
Yes, right. I'm saying that's very easy to code in perl 5.
@foo = (1, 2, 3);
@bar = (1, 2, 3);
@baz = (1, 2, 3);
$ai = aiter (@foo, @bar, @baz);
while ( ($foo,$bar,$baz) = &$ai )
{
print "OK\n" if $foo == $bar && $bar == $baz;
}
>From my library: (feel free to copy&paste into yours)
#---> $array_iterator = aiter(@a, @b, @c, ...);
# aiter : Creates an array iterator to return the elements of a set of
# arrays in turn. That is, the first time it is called, it returns
# the first element of each array. The next time, it returns the
# second elements. And so on, until all elements are exhausted.
#
# This is useful for looping over more than one array at once:
# $ai = aiter(@a, @b);
# while ( ($a,$b) = $ai->() ) { .... }
sub aiter (\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@)
{
my @arr_list = @_; # The list of (references to the) arrays
my $index = 0; # Which one the caller will get next
my $max_num = 0; # Number of elements in longest array
# Get the length of the longest input array
foreach (@arr_list)
{
$max_num = @$_ if @$_ > $max_num;
}
# Return the iterator as a closure wrt the above variables.
return sub
{
my $i = $index++;
return () if $i >= $max_num; # No more elements to return
return map $_->[$i], @arr_list; # Return ith elements
}
}
----------------------------------------------------------------------
Eric J. Roode [EMAIL PROTECTED]
Senior Software Engineer, Myxa Corporation