按值进行简单哈希搜索
我有一个简单的散列,并且想根据 $value 标准返回 $key 。也就是说,对于第 14 行,我需要什么代码来返回 $key(其中 $value 为“黄色”)?
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? ";
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}}.\n";
13 print "The kiwi is $fruit{kiwi}.\n";
14 print "What is yellow? ";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
grep
是完成这项工作的正确工具:grep
is the right tool for this job:我不太确定使用单向哈希是否可以轻松有效地完成这一任务。哈希的全部要点是将键转换为值(如果您正在查看幕后,则将其转换为值的位置)。您可以对所有值进行详尽的搜索,同时收集键,但这不如哈希查找那么有效。
为了有效地采用另一种方式,您可能需要考虑双向哈希,例如:
I'm not so sure that's easy to do efficiently with a one-way hash. The whole point of a hash is to convert the key into a value (or position of the value if you're looking under the covers). You can do an exhaustive search over all the values, collecting the keys as you go but that's not as efficient as a hash lookup.
In order to go the other way efficiently, you might want to consider a two-way hash, something like:
所以你可以这样称呼它:
So you could call it like so:
由于某些值是数组,因此您需要检查这一点。
调用:
子例程:
使用正则表达式代替 eq 是可选的,只需注意保持相同的大小写,因为
Yellow
和黄色
被认为是不同的键。Since some of your values are arrays, you need to check for that.
Calling:
The subroutine:
Using a regex instead of eq is optional, just be mindful of keeping the same case, since
Yellow
andyellow
are considered different keys.我注意到你的例子引用了匿名数组,所以我只会做一个冗长的 foreach/if 循环:
I note your example has references to anonymous arrays, so I would just do a long winded foreach/if loop: