Home: Perl Programming Help: Intermediate:
Search Hash of Arrays - using Grep



sriharsha_12
Novice

Sep 25, 2013, 12:37 AM


Views: 2807
Search Hash of Arrays - using Grep

Say I've a hash (hash of arrays),

Code
%hashSample = 
(
1 => ["AB, "XY"],
2 => ["BC, "YZ"],
3 => ["CA, "ZX"]
);

I need the find the key for value "AB". How do I do that using grep in PERL?


BillKSmith
Veteran

Sep 25, 2013, 10:14 AM


Views: 2796
Re: [sriharsha_12] Search Hash of Arrays - using Grep

It requires nested greps.

Code
use strict; 
use warnings;
my %hashSample = (
1 => ["AB", "XY"],
2 => ["BC", "YZ"],
3 => ["CA", "ZX"],
);

(my $hashkey) = grep {
grep {$_ eq 'AB'} @{$hashSample{$_}}}
keys %hashSample;
print $hashkey, "\n";


Note: The outer grep must be in list context even if you only want one key. If there is more than one match, this code will return the first of them.
Good Luck,
Bill


sriharsha_12
Novice

Sep 25, 2013, 11:38 PM


Views: 2785
Re: [BillKSmith] Search Hash of Arrays - using Grep

Thanx Bill. It works perfect.