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: Intermediate:
Adding Column values and more (not spam thankyou!)

 



lkhlc
New User

Dec 2, 2013, 8:13 PM

Post #1 of 3 (882 views)
Adding Column values and more (not spam thankyou!) Can't Post

Seeking help for the following. Appreciation is massive!

Presented with a flat file that contains two columns.
Column one is a part number.
Column two is a quantity number.
The site contains numerous duplicate part numbers from
various locations. (location itself does not matter)
The need is for a fast a painless way to generate a single
entry for each part number , having totaled the quantity
number, so five locations can be merged into one part number
to show how many total of each part number is 'in stock'.

Example of file:
04054017280,22
04054017500,29
04054018280,94
04054017280,12
04054017500,19
04054018280,24

Desired output:
04054017280,34
04054017500,48
04054018280,118

The file can be anywhere from a few k's to many megs in size.

Seeking a simple, fast and low resources snippet if possible. The output will write to a file. Comma separated data.

Thank you very much for your help in this matter.


Kenosis
User

Dec 2, 2013, 9:33 PM

Post #2 of 3 (877 views)
Re: [lkhlc] Adding Column values and more (not spam thankyou!) [In reply to] Can't Post


Code
use strict; 
use warnings;

my ( %hash, @vals );

while (<>) {
chomp;
$hash{ $vals[0] } += $vals[1] if @vals = split /,/;
}

print "$_,$hash{$_}\n" for sort { $a <=> $b } keys %hash;

Usage: perl script.pl inFile >outFIle

Output on your dataset:

Code
04054017280,34 
04054017500,48
04054018280,118


Hope this helps!


(This post was edited by Kenosis on Dec 2, 2013, 9:43 PM)


lkhlc
New User

Dec 2, 2013, 9:40 PM

Post #3 of 3 (870 views)
Re: [Kenosis] Adding Column values and more (not spam thankyou!) [In reply to] Can't Post

Bless you! thank you very much, will run in the morning..

 
 


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

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