Reputation: 41
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
Upvotes: 4
Views: 11974
Reputation: 820
@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
Upvotes: 0
Reputation: 91373
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.
Upvotes: 6
Reputation: 483
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
Upvotes: 0