按值进行简单的哈希搜索 [英] Simple hash search by value

查看:22
本文介绍了按值进行简单的哈希搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的哈希值,想根据 $value 标准返回 $key.也就是说,对于第 14 行,我需要什么代码来返回 $value 为黄色"的 $key?

I have a simple hash, and would like to return the $key based on $value criteria. That is, for line 14, what code would I need to return the $key where the $value is "yellow"?

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}}.
";
13 print "The kiwi is $fruit{kiwi}.
";
14 print "What is yellow? ";

推荐答案

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

grep is the right tool for this job:

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

my ($any_match) = grep { $fruit{$_} eq 'yellow' } keys %fruit;

这篇关于按值进行简单的哈希搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆