Perl:哈希引用访问键数组 [英] Perl: Hash ref accessing array of keys

查看:117
本文介绍了Perl:哈希引用访问键数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个似乎很基本的问题,但我无法弄清楚。假设我在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)

更多示例请参见切片perllol文档

在Perlref文档中使用引用给出了一般规则。

"Using References" in the perlref documentation gives the general rules.


1。无论你在哪里放置一个标识符(或者标识符链)作为变量或子程序名称的一部分,都可以用包含正确类型引用的简单标量变量替换标识符。

1. Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a simple scalar variable containing a reference of the correct type.

这解释了为什么(1)有效:用简单的标量 $替换了标识符 testHash hashRef

This explains why (1) works: you replaced the identifier testHash with the simple scalar $hashRef.


2。无论您将标识符(或标识符链)作为变量或子例程名称的一部分放置在任何位置,都可以使用BLOCK来替换标识符,以返回正确类型的引用。

2. Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a BLOCK returning a reference of the correct type.

上面的代码片段(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:哈希引用访问键数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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