在Perl中,我怎么创建哈希值,它的键来自给定阵列? [英] In Perl, how do I create a hash whose keys come from a given array?

查看:268
本文介绍了在Perl中,我怎么创建哈希值,它的键来自给定阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个数组,我知道我会做很多的是否数组包含X?检查。高效的方法,这样做是把该数组的一个哈希,其中的键是数组的元素,然后你就可以说

如果($哈希{X}){...} 

有没有一种简单的方法来做到这一点的阵列到哈希转换?理想情况下,它应该是灵活,足以采取匿名数组,并返回一个匿名的哈希值。


解决方案

 %哈希=地图{$ _ => 1} @array;

这不是短了@hash {} @array = ...的解决方案,但那些那些需要的哈希和阵列已经在其他地方定义的,而这其中可以采取匿名数组,并返回一个匿名哈希值。

这样做是取各元素的阵列中,并用1配对它。当这个列表(键1,键1,键1)对获得分配给散列,奇数那些成为散列的密钥,和偶数那些成为各自的值

Let's say I have an array, and I know I'm going to be doing a lot of "Does the array contain X?" checks. The efficient way to do this is to turn that array into a hash, where the keys are the array's elements, and then you can just say

if($hash{X}) { ... }

Is there an easy way to do this array-to-hash conversion? Ideally, it should be versatile enough to take an anonymous array and return an anonymous hash.

解决方案

%hash = map { $_ => 1 } @array;

It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash.

What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.

这篇关于在Perl中,我怎么创建哈希值,它的键来自给定阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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