By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,777 Members | 1,755 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,777 IT Pros & Developers. It's quick & easy.

Grouping with Perl

P: 2
Hi,

I am having some difficulty thinking of a way to do something that I'm sure is simple. I, however, just cannot get my brain around a way to get Perl to do it. What I have is a file with multiple records. The records contain an ID, name, description, application in that order. There are in some cases several of the same ID listed because one ID may have more than one application. What I want to do is print out the same data to anohter file but I want the ID's listed only once and all of the applications listed in the one line. So basically the data looks like this:

ID, name, description, application
1, XYZ, desc, PDF
1, XYZ, desc, QFZ
2, YGH, desc, LMN

What I'm looking for is:

1, XYZ, desc, PDF,QFZ
2, YGH, desc, LMN

I have been trying to think of a good way to do this for a while and haven't come up with anything. If anyone could help, I'd very much appreciate it.
Sep 10 '08 #1
Share this Question
Share on Google+
3 Replies


numberwhun
Expert Mod 2.5K+
P: 3,503
Just so we know how far you have gotten in your attempts to do this, why not post the code you have been working with, here, enclosed in code tags, and we will help you get it working from there.

Regards,

Jeff
Sep 10 '08 #2

eWish
Expert 100+
P: 971
I would suggest that you use a hash of hashes.

--Kevin
Sep 10 '08 #3

P: 2
Just so we know how far you have gotten in your attempts to do this, why not post the code you have been working with, here, enclosed in code tags, and we will help you get it working from there.

Regards,

Jeff
I already got the code going. Thanks for the helpful reply though. The code that ended up working, in case anyone else runs across this type of situation, is:

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl -w
  2.  
  3. open (IN, "input file");
  4.  
  5. while(<IN>){ 
  6.      chomp;
  7.       @t=split(/\t/,$_);
  8.       $AB{$t[0]}=$AB{$t[0]}.",$t[2]";
  9.       }
  10.       print %AB;
  11. close IN;
  12. close OUT;
  13.  
  14.  
  15. open (OUT, ">output file");
  16. open (IN, "input file");
  17.  
  18. while (<IN>){
  19.       chomp;
  20.       @Products=split(/\t/,$_);
  21.  
  22.       if ($Products[0] and exists $AB{$Products[0]}){
  23.       print OUT "$Products[0]\t$Products[2]\t$AB{$Products[0]}\n";
  24.       }
  25. }
  26.  
  27. close IN;
  28. close OUT;
Sep 10 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.