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:
Calculations

 



bhuffman
newbie

Jul 9, 2001, 10:04 PM

Post #1 of 3 (1040 views)
Calculations Can't Post

I need to total numbers that are within the same column. My program takes inputs and moves them into the proper column using a csv file, I need to have each column totaled. My csv files are separated by commas. Is there a way to do this? This is for a budgeting project and I need to make totals for each budget line and its subcatagories.

Thank you.




PerlKid
stranger

Jul 9, 2001, 10:44 PM

Post #2 of 3 (1037 views)
Re: Calculations [In reply to] Can't Post

How are you reading/writing to the file? Are you using a module for this application (ie, DBD::CSV ??) or just some home-grown program? It's hard to provide specific answers to vague questions.

--Drew
http://www.camelsoup.com

Code
s;[\d\$&(\^)];;g+s;\.; ;g+s;(.)(..);$2$1;g+print,if$_='&61k4I.)l6il.edn7(K2e^ny$';



mhx
Enthusiast / Moderator

Jul 9, 2001, 11:00 PM

Post #3 of 3 (1036 views)
Re: Calculations [In reply to] Can't Post

Hi,

the following code snippet contains only a very simple CSV parser. But if your CSV's only contain numbers separated by commas (and optionally whitespaces), it should work fine.

Code
#!/bin/perl -w 
use strict;

my $csv = 'test.csv'; # Your CSV file
my @total; # Array to hold totals

# Open the file and calculate
# the sum over each column
open CSV, $csv or die "cannot open $csv: $!\n";
while( <CSV> ) {
my $i;
$total[$i++] += $_ foreach split /\s*,\s*/;
}
close CSV;

# Print the line of totals
{ local $" = ', '; print "@total\n" }

For a CSV file

Code
1, 2, 3, 4, 5, 6, 7, 8, 9 
1, 2, 3, 4, 5, 6, 7, 8, 9
9, 7, 5, 3, 1, 2, 4, 6, 8

this will generate

Code
11 11 11 11 11 14 18 22 26

If your CSVs are more complex, you could think of using one of the many CSV interfaces available from CPAN.
Hope this helps.

-- Marcus


 
 


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

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