4

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

2
  • 2
    See List::Util::sum. Commented Jan 23, 2014 at 4:37
  • What do you mean by "return me 200+500"? Do you want the routine to actually return a running total or are you only interested in the final sum of the numbers in the array? Commented Jan 23, 2014 at 5:15

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0
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

Comments

0
@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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.