如何将数组的数组添加到哈希值

时间:2013-06-08 07:43:18

标签: arrays hash perl-data-structures

我有一个数组a1和一个数组数组a2。

@a1 = [1,2,3,4,5] 

@a2 = [ [adf],[bcg],[yet],[gpd],[iop]]

现在我想要一个散列,其中a1是键,a2的数组作为值。我该怎么做?

2 个答案:

答案 0 :(得分:0)

以下是一些方法。你的语法有点偏离,所以我假设我的变量声明就是你想要的。

my @a1 = (1,2,3,4,5);
my @a2 = ( ["a", "d", "f"], ["b", "c", "g"], ["y","e","t"], 
           ["g", "p", "d"], ["i", "o", "p"] );
# Thus $a2[0][1] => "d", etc.                                                                                                                                           

#Perl 5.12 and higher you can use "each" on an array
my %a3;
while (my ($a1_index, $a1_value) = each @a1) {
    $a3{$a1_value} = $a2[$a1_index];
}
# Now @{$a3{4}} => ["g", "p", "d"] for example

# Before 5.12 you would have to do something like this:
my %a4;
for my $i (0..$#a1) {
    $a4{$a1[$i]} = $a2[$i];
}
# Now @{$a4{4}} => ["g", "p", "d"]

答案 1 :(得分:0)

my @keys = (1,2,3,4,5);
my @vals = ( ["a", "d", "f"], ["b", "c", "g"], ["y","e","t"], 
           ["g", "p", "d"], ["i", "o", "p"] );

my $hash={};

for(my $i = 0; $i < scalar(@keys); $i++){

    $hash->{$keys[$i]}=$vals[$i];
}

#print the resulted hash
use Data::Dumper;print Dumper($hash);

结果如下: $ VAR1 = {           '4'=&gt; [                    'G',                    'P',                    'd'                  ]           '1'=&gt; [                    '一个',                    'D',                    'F'                  ]           '3'=&gt; [                    'Y',                    'E',                    'T'                  ]           '2'=&gt; [                    'B',                    'C',                    'G'                  ]           '5'=&gt; [                    '一世',                    'O',                    'P'                  ]         };

Perl哈希是无序的,所以不要担心它们在这里打印的顺序,如果需要,你可以根据数字键对它们进行排序。