Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

how to calculate the data?
if ($row ne 0) { $number = 0; while (($number) = $sth->fetchrow_array()) { $number++; $numbergraf++; my $newno = substr($number, 0, 2); $output .=qq~ The sum of xxx is $newno ~;
How do I get the sum of all the data form $newno? If I write print $newno .... I get the list of number for example 23 34 45 33 .... How do I make the code to do this(23+ 34 +45 +33+ ....) and give me an answer. Thanks

Replies are listed 'Best First'.
Re: calculate all the data
by thedoe (Monk) on Feb 20, 2005 at 06:38 UTC
    if the only thing you are doing with the data from your SQL query is calculating the sum, you could use the database's sum function for a much more efficient result.
Re: calculate all the data
by Zaxo (Archbishop) on Feb 20, 2005 at 05:10 UTC

    I think you are confusing the parts your different variables play. Is this what you want?

    my $newno = 0; while (my ($number) = $sth->fetchrow_array) { $numbergraf++; # whatever that is $newno += $number; } $output .= qq~ The sum of xxx is $newno ~;

    I'm not sure what you're trying to do with substr, but it doesn't look consistent with a sum.

    After Compline,
    Zaxo

Re: calculate all the data
by sh1tn (Priest) on Feb 20, 2005 at 05:08 UTC
    $nums = '23 34 45 33'; $sum += $_ for split ' ', $nums;

    Please, take a look at perldoc perlop