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
while (Hope that helps :)) { ($siteID, $siteAge, $siteDistance) = (split/,/)[0,1]; $hash{$siteID} += $siteAge; $tot += $siteAge; } print $tot, "\n";
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 :)
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