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.