如何在Perl中仅获得哈希的一部分? [英] How can I get a only part of a hash in Perl?

查看:73
本文介绍了如何在Perl中仅获得哈希的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法获得子哈希?我需要使用哈希片吗?

Is there a way to get a sub-hash? Do I need to use a hash slice?

例如:

%hash = ( a => 1, b => 2, c => 3 );

我只想要

%hash = ( a => 1, b => 2 );

推荐答案

哈希切片返回与键列表关联的值.要获取哈希切片,请将标记更改为@并提供键列表(在本例中为"a""b"):

Hash slices return the values associated with a list of keys. To get a hash slice you change the sigil to @ and provide a list of keys (in this case "a" and "b"):

my @items = @hash{"a", "b"};

通常您可以使用引号运算符生成列表:

Often you can use a quote word operator to produce the list:

my @items = @hash{qw/a b/};

您还可以分配给一个哈希切片,因此,如果您想要一个包含另一个哈希的子集的新哈希,您可以说

You can also assign to a hash slice, so if you want a new hash that contains a subset of another hash you can say

my %new_hash;
@new_hash{qw/a b/} = @hash{qw/a b/};

许多人会使用地图代替哈希切片:

Many people will use a map instead of hash slices:

my %new_hash = map { $_ => $hash{$_} } qw/a b/;

从Perl 5.20.0开始,如果使用%sigil而不是@ sigil,则可以一步获得键和值:

Starting with Perl 5.20.0, you can get the keys and the values in one step if you use the % sigil instead of the @ sigil:

my %new_hash = %hash{qw/a b/};

这篇关于如何在Perl中仅获得哈希的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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