Question

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?

Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top