CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



marianna1010
New User

Feb 15, 2016, 6:33 AM

Post #1 of 6 (1159 views)
Post deleted by marianna1010

 


Chris Charley
User

Feb 15, 2016, 8:29 AM

Post #2 of 6 (1151 views)
Re: [marianna1010] Perl counting [In reply to] Can't Post

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

Post #3 of 6 (1137 views)
Post deleted by marianna1010 [In reply to]

 


Laurent_R
Veteran / Moderator

Feb 16, 2016, 2:44 AM

Post #4 of 6 (1122 views)
Re: [marianna1010] Perl counting [In reply to] Can't Post

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

Post #5 of 6 (1114 views)
Post deleted by marianna1010 [In reply to]

 


BillKSmith
Veteran

Feb 16, 2016, 8:07 AM

Post #6 of 6 (1103 views)
Re: [marianna1010] Perl counting [In reply to] Can't Post

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

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives