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: Need a Custom or Prewritten Perl Program?: I need a program that...:
Add successive entries

 



mgpg
Novice

Mar 12, 2008, 12:25 PM

Post #1 of 2 (2107 views)
Add successive entries Can't Post

Hi, I have the following input:

A,1
A,4
A,2
B,3
B,0
C,23
...

I want to simply output A, SUM(all A entries). I already sorted this file so all A's are successive. I can write simple perl script to do this as follows:

Code
  $prev; 
$sum = 0;
$line =~ /(\w+),(\d+)/; $cur = $1; $n = $2;
if ($cur == $prev) { $sum += $n;}
else { print "$prev, $sum\n"; $sum = $n; }
$prev = $cur;
# loop


This is probably not the most efficient but something like this will work I think. I wonder if I can write a one-liner from command line to do this.

Thanks.


KevinR
Veteran


Mar 13, 2008, 12:22 AM

Post #2 of 2 (2100 views)
Re: [mgpg] Add successive entries [In reply to] Can't Post

Use a hash. Assuming the file is sorted with all A entries first:


Code
my %hash; 
open (IN, 'file') or die "$!";
while(<IN>){
my ($k,$v) = split(/,/);
last if ($k ne 'A');
$hash{$k}+=$v;
}
close IN;
print "A = $hash{A}";


If all you wanted were the A lines you could grep the file to get only the A lines then apply the above code. It probably could be done with a one liner too. I will leave that up to you.
-------------------------------------------------

 
 


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

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