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: Beginner:
How do I get elements of a hash whose keys match a given regex?

 



alferic
Novice

Oct 2, 2013, 6:46 AM

Post #1 of 5 (934 views)
How do I get elements of a hash whose keys match a given regex? Can't Post

How do I get elements of a hash whose keys match a given regex?

I tried below script but it will not display the value.

my %hash = (
king => 1 ,
queen => 2,
);
my $regex =~ /queen/;

if (grep {/$regex/} keys %hash)
{
print "value is: $hash{$_}\n";
}
else
{
print "not found..\n";
}


FishMonger
Veteran / Moderator

Oct 2, 2013, 10:38 AM

Post #2 of 5 (923 views)
Re: [alferic] How do I get elements of a hash whose keys match a given regex? [In reply to] Can't Post

Tie::Hash::Regex - Match hash keys using Regular Expressions
http://search.cpan.org/~davecross/Tie-Hash-Regex-1.02/lib/Tie/Hash/Regex.pm


2teez
Novice

Oct 2, 2013, 10:41 AM

Post #3 of 5 (923 views)
Re: [alferic] How do I get elements of a hash whose keys match a given regex? [In reply to] Can't Post

You can do like thus:

Code
use strict; 
use warnings;

my %hash = (
king => 1 ,
queen => 2,
);

my $given_regex = qr/queen/; ## NOTE THIS
## use a map

print map{$hash{$_},$/ if/$given_regex/} keys %hash;

## use a for loop

for(keys %hash){
print $hash{$_},$/ if /$given_regex/;
}



Laurent_R
Veteran / Moderator

Oct 3, 2013, 10:43 AM

Post #4 of 5 (913 views)
Re: [alferic] How do I get elements of a hash whose keys match a given regex? [In reply to] Can't Post

Just as an additional information on the errors in your code, you don't quite understand the grep syntax.

The grep function takes a list of values on its right and passes on its left the values for which the grep block returned true.

Second point, your $regex is not initialized correctly, you should use the assignment operator, not the match operator for that.

So you could have done this:

Code
my $regex = qr/queen/;  
my @matching_keys = grep {/$regex/} keys %hash;


Now, the @matching_keys array contains the values which matched the regex (just one, queen, in your case).


alferic
Novice

Oct 4, 2013, 6:10 AM

Post #5 of 5 (907 views)
Re: [Laurent_R] How do I get elements of a hash whose keys match a given regex? [In reply to] Can't Post

Thanks Gurus for the advises! I experimented and able to get what I want:
my %hash = (
king => 1 ,
queen => 2,
);
my $value ="";

my ($matching_key) = grep { $_ =~ /queen/ } keys %hash;

$value = $hash{$matching_key};

print "$value\n";

 
 


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

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