Simple Totals Example (Help Needed)
doctormaze
created: 2006-04-02 18:45:43
In order to learn Perl, I've started fiddling 
around with text files.  I have a file called-

 siteperf.txt

, Which contains this data-

 A,5000,20
 B,4500,15
 C,4000,10

All, I want to do is total the values in the
second column.

So far I've come up with this-

 $sitePerf = 'siteperf.txt';
 $tot = 0;
 open(F, "$sitePerf") || die ("Could not open $sitePerf!");
 while ()
 {
  ($siteID, $siteAge, $siteDistance) = (split/,/)[0,1];
  $tot = $hash{$siteID} += $siteAge;
  print $tot;
 }
 close (F);

, Instead of added the data in the second column ($siteAge)
together, the script justs concatenates the values and
prints-
 
 500045004000

Your expertise is appreciated,. I've got lots of Perl
books out and have been diligently trawling the internet
and this is very frustrating!

Thanks
Re: Simple Totals Example (Help Needed)
created: 2006-04-02 18:54:05
two things:
  1. you should increase $tot, instead of assigning it the current value of $hash{$siteID}
  2. you should print $tot outside the while; also, try adding a newline; that would visualise what happens now
In code:
 while ()
 {
  ($siteID, $siteAge, $siteDistance) = (split/,/)[0,1];
  $hash{$siteID} += $siteAge;
  $tot += $siteAge;
 }
 print $tot, "\n";
Hope that helps :)
Re^2: Simple Totals Example (Help Needed)
created: 2006-04-02 19:06:02
Thanks, much appreciated!!!
};->
p.s. Incredibly quick reply!
Re: Simple Totals Example (Help Needed)
created: 2006-04-02 19:46:41
You already have an answer to your question, but as you're new to Perl - here is a little bit of extra advice :)

Try to get into the habit of including:

use strict;
use warnings;
at the start of every program and script that you write. By [doc://use]ing [doc://strict] and [doc://warnings], you will save yourself many "head-banging" moments. For a good discussion on this, have a read of [id://482733] and the ensuing thread.

Cheers,
Darren :)

Re: Simple Totals Example (Help Needed)
created: 2006-04-03 02:13:20

Here's a "one liner" solution:

perl -naF, -e "$t += $F[1]; eof and print $t;" siteperf.txt

If you wrote that out "the long way", here's how it would look:

while ( <> ) {
    @F = split ',';
    $t += $F[1];
    eof and print $t;
}
# Usage: perl mytally.pl siteperf.txt

Within the one-liner, the -n flag is responsible for creating a while( <> ) {.... loop. The -a flag is responsible for creating a @F = split ','; statement. And because the -n loop wraps a loop around all the code, a test must be conducted to spot the end of the file, and print the resulting tally only on the last loop iteration.


Dave

perlmonks.org content © perlmonks.org and davido, doctormaze, McDarren, rhesa

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03