按值进行简单哈希搜索

kur*_*uki 19 perl hash search grep

我有一个简单的哈希,并希望根据$ value条件返回$ key.也就是说,对于第14行,我需要返回$ key为"黄色"的$ key的代码?

1  #!/usr/bin/perl
2
3  # This program creates a hash then
4  # prints out what is in the hash
5
6  %fruit = (
7   'apple' => ['red','green'],
8   'kiwi' => 'green',
9   'banana' => 'yellow',
10  );
11
12 print "The apple is @{$fruit{apple}}.\n";
13 print "The kiwi is $fruit{kiwi}.\n";
14 print "What is yellow? ";
Run Code Online (Sandbox Code Playgroud)

soc*_*pet 21

grep 是这项工作的正确工具:

my @all_matches = grep { $fruit{$_} eq 'yellow' } keys %fruit;
print("$_ ") foreach @matching_keys;

my ($any_match) = grep { $fruit{$_} eq 'yellow' } keys %fruit;
Run Code Online (Sandbox Code Playgroud)

  • `print"$ _"foreach @ matching_keys`更好地写成`print"@matching_keys"`,没有作为奖励的尾随空格.此外,codaddict是正确的,grep将不适用于数组引用的值. (3认同)