问题描述
我有一个似乎很基本的问题,但我无法弄清楚。假设我在Perl中有一个哈希引用。我想通过一组键来获取一组值。
I have a question that seems basic, but I can't figure out. Say that I have a hash reference in Perl. I want to get an array of values through an array of keys.
以下是它如何使用散列,而不是散列引用:
Here's how it'd work with a hash, not a hash reference:
my %testHash = ( "a" => 1, "b" => 2, "c" => 3 );
my @testKeys = ("a", "b", "c");
my @testValues = @testHash{@testKeys};
现在假设我有一个散列引用,
Now suppose I have a hash reference,
my $hashRef = {"a" => 1, "b" => 2, "c" => 3};
我尝试了以下两种方式:
I've tried the following two ways:
my @values = @{$hashRef->{@testKeys}};
my @values = $hashRef->{@testKeys};
但这两个都不正确。有没有一个正确的方法,或者我只需要在每次我想要这样做时都取消引用散列ref?
But neither is correct. Is there a correct way, or do I just have to dereference the hash ref every time I want to do this?
推荐答案
您'关闭:
my @values = @$hashref{@testKeys}; ## (1)
或
my @values = @{$hashref}{@testKeys}; ## (2)
更多示例请参见。
给出了一般规则。
"Using References" in the perlref documentation gives the general rules.
这解释了为什么(1)有效:用简单的标量 $替换了标识符
。 testHash
hashRef
This explains why (1) works: you replaced the identifier testHash
with the simple scalar $hashRef
.
上面的代码片段(2)几乎相同,但语法较为庞大。代替标识符 testHash
,您可以编写一个返回散列引用的块, ie , {$ hashRef}
。
Snippet (2) above is nearly the same but has a little bulkier syntax. In place of the identifier testHash
, you write a block returning a reference to a hash, i.e., {$hashRef}
.
这里的大括号包含一个善意的块,所以您可以计算并返回一个引用,如
The braces here enclose a bona fide block, so you can compute and return a reference, as in
push @{ $cond ? \@a1 : \@a2 }, "some value";
这篇关于Perl:哈希引用访问键数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!