How can I sum arrays element-wise in Perl?

Dmytro Leonenko picture Dmytro Leonenko · Dec 8, 2009 · Viewed 17.9k times · Source

I have two arrays:

@arr1 = ( 1, 0, 0, 0, 1 );
@arr2 = ( 1, 1, 0, 1, 1 );

I want to sum items of both arrays to get new one like

( 2, 1, 0, 1, 2 );

Can I do it without looping through arrays?

Answer

catwalk picture catwalk · Dec 8, 2009

for Perl 5:

use List::MoreUtils 'pairwise';
@sum = pairwise { $a + $b } @arr1, @arr2;