[英]In a large Perl hash, how do I extract a subset of particular keys?
I have a large hash and have a subset of keys that I want to extract the values for, without having to iterate over the hash looking for each key (as I think that will take too long). 我有一个大的哈希,并有一个我想要提取值的键的子集,而不必迭代哈希查找每个键(因为我认为这将花费太长时间)。
I was wondering if I can use grep
to grab a file with a subset of keys? 我想知道我是否可以使用
grep
来获取带有一个键子集的文件? For example, something along the lines of: 例如,有些东西:
my @value = grep { defined $hash{$_}{subsetofkeysfile} } ...;
Use a hash slice: 使用哈希切片:
my %hash = (foo => 1, bar => 2, fubb => 3);
my @subset_of_keys = qw(foo fubb);
my @subset_of_values = @hash{@subset_of_keys}; # (1, 3)
Two points of clarification. 两点澄清。 (1) You never need to iterate over a hash looking for particular keys or values.
(1)您永远不需要遍历查找特定键或值的哈希。 You simply feed the hash a key, and it returns the corresponding value -- or, in the case of hash slices, you supply a list of keys and get back a list of values.
您只需向哈希提供一个密钥,然后返回相应的值 - 或者,如果是哈希切片,则提供密钥列表并返回值列表。 (2) There is a difference between
defined
and exists
. (2)已
defined
和exists
之间exists
差异。 If you're merely interested in whether a hash contains a specific key, exists
is the correct test. 如果您只关心散列是否包含特定键,则
exists
是正确的测试。
If the hash may not contain any keys from the subset, use a hash slice and grep: 如果散列可能不包含子集中的任何键,请使用散列片和grep:
my @values = grep defined, @hash{@keys};
You can omit the grep part if all keys are contained in the hash. 如果散列中包含所有键,则可以省略grep部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.