Home: Perl Programming Help: Beginner:
Post deleted by marianna1010

marianna1010
New User

Feb 15, 2016, 6:33 AM

Views: 1919
 Post deleted by marianna1010

Chris Charley
User

Feb 15, 2016, 8:29 AM

Views: 1911
 Re: [marianna1010] Perl counting
The problem is you are assigning to a new array for each iteration of the loop. Declare @sum before the loop, and then push each calculation onto the array.

Then you could use 'sum' from List::Util to calculate the sum of the items.

Or, you could just keep a variable in the for loop to accumulate the sum at each iteration of the loop.
 Code
`use List::Util 'sum';  my \$min_depth = 1; my \$max_depth = 5; my \$size = 3;  my @tab = (\$min_depth..\$max_depth); my @sum;   foreach (@tab) {  	push @sum, \$size**\$_; }   print "@sum = ", sum @sum;`
If you really don't need the array (except to calculate the sum), you could write this instead.
 Code
`my \$sum;   foreach (@tab) {  	\$sum += \$size**\$_; }   print "sum = \$sum\n";`
I can think of other ways to do this, but the solutions above should be enough.

marianna1010
New User

Feb 15, 2016, 1:57 PM

Views: 1897
 Post deleted by marianna1010

Laurent_R
Veteran / Moderator

Feb 16, 2016, 2:44 AM

Views: 1882
 Re: [marianna1010] Perl counting
Not quite sure what you mean, but you could try this:

 Code
`\$ perl -E 'my (\$min, \$max) = @ARGV; my \$sum; \$sum += 3**\$_ for \$min..\$max; say \$sum;' 1 5 363`

marianna1010
New User

Feb 16, 2016, 6:59 AM

Views: 1874
 Post deleted by marianna1010

BillKSmith
Veteran

Feb 16, 2016, 8:07 AM

Views: 1863
 Re: [marianna1010] Perl counting
The code that you have posted does not print the output that you show. This is part of the reason that we ask you to post a complete script that we can run and duplicate your problem. Here is a minimum script which includes your code. I am including the windows commands to display and execute it so there is no doubt that I am executing the code that I post.

 Code
`C:\Users\Bill\perl\guru>type marianna1010_2.pl use strict; use warnings; my \$min_depth = 1; my \$max_depth = 5; my @tab = (\$min_depth..\$max_depth); my \$sum; my \$size=3;  foreach (@tab) {         \$sum += \$size**\$_; }  print "sum = \$sum\n";    C:\Users\Bill\perl\guru>perl marianna1010_2.pl sum = 363  C:\Users\Bill\perl\guru>`

Note that the printout is exactly what you requested. Please let us know whether or not you are able to reproduce this demo.
Good Luck,
Bill