简体   繁体   中英

Returning sum of array elements perl

I have an MyArray whoes content are "200 500 800 100 " in perl . I need function which return me first 200, second iteration it should return me 200+500, next time it should return me 200+500+800,until it has sumup all the elements.

   foreach my $i (0 .. $#MyArray)
   {
       @MyArray = (1..$i);     
       $sum += $_ for @MyArray;
   }

I am trying to do something as mentioned above, but its not returning any $sum

How about:

use List::Util qw/sum/;
my @arr = (200, 500, 800, 100);
say sum(@arr[0..$_]) for (0..$#arr);

Output:

200
700
1500
1600

Documentation about List::Util .

my $array = [200, 500, 800, 100];
my @sum_array;
my $iter_sum = 0;
for my $each (@$array) {
    $iter_sum += $each;
    push @sum_array, $iter_sum;
}
return \@sum_array;

you can get the sum in the @sum_array

@MyArray = (1..10);
foreach my $i (0 .. $#MyArray)
{
        $sum += $_ for @MyArray;
}
print "sum: $sum"

Output:

sum: 550

About your code: Maybe you need to put the array definition out of loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM