perl - 从两个数组创建一个散列 [英] perl - creating a hash from two arrays

查看:139
本文介绍了perl - 从两个数组创建一个散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  root rhino root root root root root root root root root root domainte root 
stam rhino jam onetwo domante ftpsi jay testwp contra raul vnod foos raul bruce

请注意,它们长度相等(并且总是)。我想创建一个哈希值,以便有一个名为 root 的键,其值是第二个数组中的相应值。基本上,第一个数组的元素需要是键,而第二个数组中的元素需要是值,但键需要是唯一的,值可以是数组。



我如何去实现这个结果?对不起,对Perl来说很新鲜。

解决方案

只需遍历两个数组的索引,将每个值推送到相应的数组

 #!/ usr / bin / perl 
使用警告;
使用strict;

使用Data :: Dumper;

my @keys = qw(root rhino root root root root root root root root root root domainte root);
my @values = qw(stam rhino jam onetwo domante ftpsi jay testwp contra raul vnod foos raul bruce);


my%hash;
为我的$ idx(0 .. $#keys){
push @ {$ hash {$ keys [$ idx]}},$ values [$ idx];
}

打印Dumper \%hash;


I have 2 arrays of the following form:

root rhino root root root root root root root root root root domainte root
stam rhino jam onetwo domante ftpsi jay testwp contra raul vnod foos raul bruce

Notice that they are of equal length (and always will be). I want to create a hash such that there is one single key called root whose values are the corresponding values from the second array. Basically, the elements of the first array need to be the keys and the elements from the second array need to be the values, but keys need to be unique and values could be an array.

How do I go about achieving this result? Sorry, quite new to to Perl.

解决方案

Just iterate over the indexes of both the arrays, pushing each value to the corresponding array reference at the key.

#!/usr/bin/perl
use warnings;
use strict;

use Data::Dumper;

my @keys   = qw(root rhino root root root root root root root root root root domainte root);
my @values = qw(stam rhino jam onetwo domante ftpsi jay testwp contra raul vnod foos raul bruce);


my %hash;
for my $idx (0 .. $#keys) {
    push @{ $hash{ $keys[$idx] } }, $values[$idx];
}

print Dumper \%hash;

这篇关于perl - 从两个数组创建一个散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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