http://qs321.pair.com?node_id=43830

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (arrays)

I want to multiply the first terms of the arrays with each other, and the two second terms with each other, etc.

Originally posted as a Categorized Question.

  • Comment on How do I multiply the corresponding elements in two arrays together?

Replies are listed 'Best First'.
Re: How do I multiply the corresponding elements in two arrays together?
by Fang (Pilgrim) on Sep 09, 2005 at 21:00 UTC

    You could use List::MoreUtils:

    use List::MoreUtils qw/pairwise/; @a = (1..5); @b = (6..10); @x = pairwise { $a * $b } @a, @b; print join ", ", @x; __END__ 6, 14, 24, 36, 50

    Be sure to check both array have the same number of elements, or you could get a trail of zeroes:

    use List::MoreUtils qw/pairwise/; @a = (1..5); @b = (6..8); @x = pairwise { $a * $b } @a, @b; print join ", ", @x; __END__ 6, 14, 24, 0, 0
Re: How do I multiply the corresponding elements in two arrays together?
by Russ (Deacon) on Nov 30, 2000 at 00:28 UTC
    I hate to use array indices, but here's one way:
    my @Products = map {$Arr1[$_] * $Arr2[$_]} 0..$#Arr1;
    This assumes that the arrays @Arr1 and @Arr2 exist and are the same length.
Re: Can I multiply corresponding numbers in two arrays together?
by rajib (Novice) on Aug 20, 2002 at 17:47 UTC
    @product; $i = 0; if ($#Arr1 == $#Arr2) { foreach(@Arr1) { $product = $_ * $Arr2[$i]; ++$i; } } else { print "Do you really want to multiply unequal length of arrays?\n"; }

    Originally posted as a Categorized Answer.