Your skill will accomplishwhat the force of many cannot PerlMonks

### How do I multiply the corresponding elements in two arrays together?

 on Nov 29, 2000 at 07:23 UTC Need Help??

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.

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://43830]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-07-14 16:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found

Notices?
 • erzuuli ‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.