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:
Search Hash of Arrays - using Grep

 



sriharsha_12
Novice

Sep 25, 2013, 12:37 AM

Post #1 of 3 (510 views)
Search Hash of Arrays - using Grep Can't Post

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

Post #2 of 3 (499 views)
Re: [sriharsha_12] Search Hash of Arrays - using Grep [In reply to] Can't Post

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

Post #3 of 3 (488 views)
Re: [BillKSmith] Search Hash of Arrays - using Grep [In reply to] Can't Post

Thanx Bill. It works perfect.

 
 


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

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