加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl:哈希参考访问密钥数组

发布时间:2020-12-15 21:30:21 所属栏目:大数据 来源:网络整理
导读:我有一个似乎基本的问题,但我无法弄清楚.说我在Perl中有哈希引用.我想通过一个键数组来获取一个数组. 以下是使用哈希而不是散列引用的方法: my %testHash = ( "a" = 1,"b" = 2,"c" = 3 );my @testKeys = ("a","b","c");my @testValues = @testHash{@testKey
我有一个似乎基本的问题,但我无法弄清楚.说我在Perl中有哈希引用.我想通过一个键数组来获取一个数组.

以下是使用哈希而不是散列引用的方法:

my %testHash = ( "a" => 1,"b" => 2,"c" => 3 );
my @testKeys = ("a","b","c");

my @testValues = @testHash{@testKeys};

现在假设我有一个哈希引用,

my $hashRef = {"a" => 1,"c" => 3};

我尝试了以下两种方式:

my @values = @{$hashRef->{@testKeys}};
my @values = $hashRef->{@testKeys};

但是两者都不正确.有没有正确的方法,或者我只需要取消引用散列引用每次我想这样做?

解决方法

你很近
my @values = @$hashref{@testKeys};     ## (1)

要么

my @values = @{$hashref}{@testKeys};   ## (2)

有关更多示例,请参阅“Slices” in the perllol documentation.

“Using References” in the perlref documentation给出了一般规则.

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)工作:用简单的标量$hashRef替换了标识符testHash.

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,你写一个返回一个散列引用的块,即{$hashRef}.

这里的大括号包含一个真正的块,所以你可以计算并返回一个引用,如in

push @{ $cond ? @a1 : @a2 },"some value";

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读