How can I sum arrays element-wise in Perl?

前端 未结 9 515
孤城傲影
孤城傲影 2020-12-15 07:53

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

<         


        
相关标签:
9条回答
  • 2020-12-15 08:36

    for Perl 5:

    use List::MoreUtils 'pairwise';
    @sum = pairwise { $a + $b } @arr1, @arr2;
    
    0 讨论(0)
  • 2020-12-15 08:36

    You've seen a C style for loop, and pairwise. Here's an idiomatic Perl for loop and map:

    my @arr1 = ( 1, 0, 0, 0, 1 );
    my @arr2 = ( 1, 1, 0, 1, 1 );
    
    my @for_loop;
    for my $i ( 0..$#arr1 ) { 
        push @for_loop, $arr1[$i] + $arr2[$i];
    }
    
    my @map_array = map { $arr1[$_] + $arr2[$_] } 0..$#arr1;
    

    I like map and pairwise best. I'm not sure that I have a preference between those two options. pairwise handles some boring details of plumbing for you, but it is not a built-in like map. On the other hand, the map solution is very idiomatic, and may be opaque to a part-time perler.

    So, no real wins for either approach. IMO, both pairwise and map are good.

    0 讨论(0)
  • 2020-12-15 08:41

    I'm not sure what you plan to do with the sum once you have it, but you plan to do more vector-y type stuff, then Math::Matrix might be a good fit.

    use Math::Matrix;
    
    my $foo = Math::Matrix->new([ 1, 0, 0, 0, 1 ]);
    my $bar = Math::Matrix->new([ 1, 1, 0, 1, 1 ]);
    my $sum = $foo->add($bar);
    
    0 讨论(0)
提交回复
热议问题