in reply to parallel procesing

I think you want a combination of zip and natatime ("n-at-a-time") from List::MoreUtils:

my $pairs = natatime 2, zip $array1, $array2; while (my (@vals) = $pairs->()) { ... };

zip "zips" together two lists, alternating the elements. natatime returns you n elements from a list.

Replies are listed 'Best First'.
Re^2: parallel procesing
by ikegami (Patriarch) on Apr 06, 2008 at 09:54 UTC
    If you're going to use List::MoreUtils for something this trivial, then each_arrayref does everything in one step.
    my $i = each_arrayref($array1, $array2); while (my ($x, $c) = $i->()) { print("$x, $c\n"); }
Re^2: parallel procesing (List::Pairwise)
by lodin (Hermit) on Apr 06, 2008 at 12:39 UTC

    Personally I prefer to use a non-iterator style, so I combine (my own) zip with pair from List::Pairwise.

    for (pair(zip($array1, $array2))) { my ($x, $y) = @$_; # It's often descriptive to name the values. ... }
    The main reason I like pair over natatime is that it's easy to combine with any expression/subroutine that requires the whole list and in particular sort (but also map and grep). For instance:
    for ( sort { $a->[0] <=> $b->[0] or $a->[1] cmp $b->[1] } pair zip($array1, $array2) ) { my ($number, $char) = @$_; ... }
    The reason I don't use zip from List::MoreUtils is that it's prototyped with (\@\@;\@...) which I find counter-intuitive, as I imagine you do too as you passed in $array1 instead of @$array1. It's also more in the way than it's helping, as I frequently end up with wanting to zip the result of an expression instead of an array or having a list or an array holding array references.

    lodin

      i have a problem with zip subroutine. I've installed mentioned modules but the zip subroutine could not be executed because it isn't there. you said "I combine (my own) zip " where is the publicly available zip situated ???

        Assuming the same number of elements in each array you could:

        push @$zip, map {shift @$_} ($array1, $array2) while @$array1;

        If you instead wanted an array of paired rather than zipped elements you could:

        push @$array, [map {shift @$_} ($array1, $array2)] while @$array1;

        Note however that both of these destroy the original arrays.


        Perl is environmentally friendly - it saves trees