Search code examples
regexperlperl-hash

check whether 'hash key string' contains a word in perl


I want to check whether a particular word is present in key of hash.

I tried in the following way:

while (($key, $value) = each(%hash))
{
   if( $key =~ /\b$some_word\b/ ) 
   {
      print"$key contains $some_word \n";
   } 
}

My question is there any built-in function for the same or is there any alternate method?


Solution

  • use warnings;
    use strict;
    
    my %hash = (
        'foo' => 1,
        'foo bar' => 2,
        'bar' => 3,
        'food' => 4
    );
    
    my $some_word = "foo";
    
    for (grep /\b\Q$some_word\E\b/, keys %hash)
    {
        print "$_ contains $some_word (value: $hash{$_})\n" 
    }
    

    Update: included value as well.

    Update 2: Thanks, kenosis, for suggesting the quote-literal modifier (\Q...\E) which is usually a good idea when putting a variable into a regex. It ensures that nothing in the variable is interpreted as a regex metacharacter.