Solved

perl lookup values from one file in another

Posted on 2013-11-12
2
309 Views
Last Modified: 2013-11-12
Hi,

I asked a question yesterday (http://rdsrc.us/JU6UCg) which was answered but I think I need to go back and start at the beginning.

I have a text file with two columns like follows (the real file has c.100k lines)

9781      Person1
978        Person2
9782      Person3
978        Person4

I then have a second text file that has one column of data as follows:

978
9781


I want to loop round this second file and using the ID lookup the corresponding line in file1 and return the value in column.  I need to loop it as one the value is retrieved I need to do further processing on it, but that’s outside this question.

Note that in file1 the data in the first column isn’t unique  - where more than 1 match is found, I want it to return a null (i.e undtermined)

So, given the IDs in file 2, I would want to retrieve:

undetermined
Person1


How do I properly read file1 into a hash and then lookup values in it whilst looping through a second file?
0
Comment
Question by:yelbow
2 Comments
 
LVL 84

Accepted Solution

by:
ozo earned 500 total points
ID: 39641554
#!/usr/bin/perl
use strict;
use warnings;
open F,"<a text file" or die $!;
my %f;
while( <F> ){
    next unless my @F=split;
    push @{$f{$F[0]}}, $F[1];
}
open F,"<second text file" or die $!;
while( <F> ){
   my($id)=/(\S+)/;
   print @{$f{$id}||[]}==1?$f{$id}[0]:"undetermined","\n";
}
0
 

Author Closing Comment

by:yelbow
ID: 39641719
Thanks, works a treat - will now go and decipher it.  Thanks again.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question