如何测试哈希中是否存在值? [英] How to test if a value exist in a hash?
问题描述
假设我有这个
#!/usr/bin/perl
%x = ('a' => 1, 'b' => 2, 'c' => 3);
我想知道值 2 是否是 %x
中的哈希值.
and I would like to know if the value 2 is a hash value in %x
.
这是怎么做到的?
推荐答案
从根本上说,哈希是一种优化用于解决相反问题的数据结构,知道键 2 是否存在.但是在不知道的情况下很难判断,所以我们假设它不会改变.
Fundamentally, a hash is a data structure optimized for solving the converse question, knowing whether the key 2 is present. But it's hard to judge without knowing, so let's assume that won't change.
此处介绍的可能性取决于:
Possibilities presented here will depend on:
- 您需要多久做一次
- 哈希的动态程度
grep $_==2, values %x
(也拼写为grep {$_==1} values %x
)将返回一个包含多个 2 的列表出现在散列中,或者在标量上下文中,匹配的数量.在条件中评估为布尔值,它会产生您想要的结果.grep
适用于我记忆中最老的 Perl 版本.use List::Util qw(first);第一个 {$_==2} 值 %x
仅返回第一个匹配项,如果没有,则返回undef
.这使它更快,因为它一旦成功就会短路(停止检查元素).这对 2 来说不是问题,但要注意返回的元素不一定评估为布尔值 true.在这些情况下使用defined
.List::Util
是一个自 5.8 起成为 Perl 核心的一部分.use List::MoreUtils qw(any);任何 {$_==2} 值 %x
都准确地以布尔值形式返回您请求的信息,并表现出短路行为.List::MoreUtils
可从 CPAN 获得.立>2 ~~ [values %x]
以布尔值形式准确返回您请求的信息,并表现出短路行为.
智能匹配自 5.10 起在 Perl 中可用.
grep $_==2, values %x
(also spelledgrep {$_==1} values %x
) will return a list of as many 2s as are present in the hash, or, in scalar context, the number of matches. Evaluated as a boolean in a condition, it yields just what you want.
grep
works on versions of Perl as old as I can remember.use List::Util qw(first); first {$_==2} values %x
returns only the first match,undef
if none. That makes it faster, as it will short-circuit (stop examining elements) as soon as it succeeds. This isn't a problem for 2, but take care that the returned element doesn't necessarily evaluate to boolean true. Usedefined
in those cases.
List::Util
is a part of the Perl core since 5.8.use List::MoreUtils qw(any); any {$_==2} values %x
returns exactly the information you requested as a boolean, and exhibits the short-circuiting behavior.
List::MoreUtils
is available from CPAN.2 ~~ [values %x]
returns exactly the information you requested as a boolean, and exhibits the short-circuiting behavior.
Smart matching is available in Perl since 5.10.
构造一个将值映射到键的散列,并将其用作自然散列来测试键是否存在.
Construct a hash that maps values to keys, and use that one as a natural hash to test key existence.
my %r = reverse %x;
if ( exists $r{2} ) { ... }
重复操作,动态散列
使用如上所述的反向查找.您需要使其保持最新状态,这留给读者/编辑作为练习.(提示:值冲突很棘手)
Repeated op, dynamic hash
Use a reverse lookup as above. You'll need to keep it up to date, which is left as an exercise to the reader/editor. (hint: value collisions are tricky)
这篇关于如何测试哈希中是否存在值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!