Link to home
Start Free TrialLog in
Avatar of yelbow
yelbow

asked on

perl "vlookup" using a hash?

Hi,

I have a text file with two columns like follows

9781      Person1
978       Person2
9782      Person3

I then have an ID that I want to look up from this file - returning the 2nd column for the first match it finds.

For example, if my ID = “978”, I want it to return “Person2” as I want it to be an exact match against columnA.

ID “9782” would then return “Person3”

Can this be done with a hash and using exist?

(This probably sounds so basic that it reads like a homework question, it’s really not!)
Avatar of wilcoxon
wilcoxon
Flag of United States of America image

Yes.  As a one-liner, this would do it.  It can be easily expanded into a script (or portion thereof).
perl -ne '($id,$per) = split; $data{$id} = $per; END { print $data{978}, "\n" if exists($data{978}) }'

Open in new window

Avatar of yelbow
yelbow

ASKER

Thanks!  I've realised I need to complicate this further - it seems that ColumnA doesn't always contain a unique value.  For example, the data could be:

9781      Person1
978       Person2
978        Person4
9782      Person3

I think a has requires a unique match on the key (?) and if not returns the last one it finds (?) (at least it seems that way!)

is there a way to return the first match it finds on $id?

(Apologies for extending the question!)
ASKER CERTIFIED SOLUTION
Avatar of wilcoxon
wilcoxon
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of yelbow

ASKER

Thanks!