in reply to Parallel processing two arrays with different numbers of elements

I call it "List::MoreUtils::pairwise".

use v5.12; use List::MoreUtils; my @arr = qw/a b c d e/; my @bar = qw/12 34 56/; my $i = 0; List::MoreUtils::pairwise { say "\t$i"; say "\t\t$a, $b"; $i++; } @arr, @bar;
use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name
  • Comment on Re: Parallel processing two arrays with different numbers of elements
  • Download Code

Replies are listed 'Best First'.
Re^2: Parallel processing two arrays with different numbers of elements
by LanX (Saint) on Sep 14, 2013 at 23:09 UTC
    > I call it "List::MoreUtils::pairwise".

    unfortunately not a perfect solution :(

    using literal list is cumbersome

    DB<260> pairwise { $a => $b } @a, @{[a..d]} => (1, "a", 2, "b", 3, "c", 4, "d")

    no warning if $a or $b is lexical

    DB<261> my $a;pairwise { $a => $b } @a, @{[a..d]} => (undef, "a", undef, "b", undef, "c", undef, "d")

    sort does it right

    DB<262> my $a; sort {$a <=>$b} reverse 1..10;; Can't use "my $a" in sort comparison at (eval 360)[multi_perl5db.pl:64 +4] line 2.

    and there is no easy way to limit size to one of the arrays like with Hyper-Operators in Perl 6

    (update)

    @a »+« @b; # @a and @b MUST be the same size @a «+« @b; # @a can be smaller, will upgrade @a »+» @b; # @b can be smaller, will upgrade @a «+» @b; # Either can be smaller, Perl will Do What You Mean

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      For literal lists, I'd probably bypass the prototype:

      &pairwise( sub { $a => $b }, \@a, ['a'..'d'], );

      Or if you need to do it a lot, maybe wrap it with a different prototype:

      sub ref_pairwise (&;@) { goto \&List::Util::pairwise } ref_pairwise { $a + $b } \@a, ['a'..'d'];

      Limiting to the size of the arrays needs to be added explicitly to the block, but isn't especially challenging:

      use v5.12; use List::MoreUtils; my @arr = qw/a b c d e/; my @bar = qw/12 34 56/; my $i = 0; List::MoreUtils::pairwise { return if $i > $#arr || $i > $#bar; say "\t$i"; say "\t\t$a, $b"; $i++; } @arr, @bar;

      (It would be more sugary if that return could be a last, but ho hum.)

      use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

        Nice, but...

        return if $i > $#arr || $i > $#bar;

        ...doesn't report "different numbers of elements."

        If I've misconstrued your question or the logic needed to answer it, I offer my apologies to all those electrons which were inconvenienced by the creation of this post.