如何在 Perl 中将两个数组分配给一个散列? [英] How can I assign two arrays to a hash in Perl?

查看:40
本文介绍了如何在 Perl 中将两个数组分配给一个散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几行代码,其中包含两个大数组(因此不能将其写入散列),我想将它们与散列连接起来.

I have lines of code with two large arrays (so can't just write it into a hash) which I want to connect with a hash.

例如,$array1[0] 成为键,$array2[0] 成为值,依此类推到 $array1[150],$array2[150].

For example, $array1[0] becomes the key and $array2[0] becomes the value and so on to $array1[150],$array2[150].

对我如何做到这一点有任何想法吗?

Any ideas how I do this?

推荐答案

您可以在一个作业中完成:

You can do it in a single assignment:

my %hash;
@hash{@array1} = @array2;

这是一个常见的成语.来自 perldoc perldata on slices:

It's a common idiom. From perldoc perldata on slices:

如果您对使用的原因感到困惑在散列切片上有一个@"一个'%',这样想.这括号类型(方形或卷曲)控制它是一个数组还是一个正在查看哈希.在另一手,前导符号('$' 或 '@')在数组或散列上指示是否你得到了一个单一的价值(标量)或复数(列表).

If you're confused about why you use an '@' there on a hash slice instead of a '%', think of it like this. The type of bracket (square or curly) governs whether it's an array or a hash being looked at. On the other hand, the leading symbol ('$' or '@') on the array or hash indicates whether you are getting back a singular value (a scalar) or a plural one (a list).

当我看到其中一个时,我会在脑海中看到拉链的图像...

When I see one of these I see a mental image of a zipper...

这篇关于如何在 Perl 中将两个数组分配给一个散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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