perl哈希与数组

时间:2014-04-01 13:19:25

标签: arrays perl perl-data-structures

我做了同样的哈希:

my %tags_hash;

然后我迭代一些地图并将值添加到@tags_hash:

if (@tagslist) {

        for (my $i = 0; $i <= $#tagslist; $i++) {
            my %tag = %{$tagslist[$i]};


            $tags_hash{$tag{'refid'}} = $tag{'name'};


        }}

但是我想拥有数组,所以当key存在时再向数组添加值。 像这样:

e.g。迭代次数

1, 
key = 1
value = "good"

{1:['good']}


2, 
key = 1
value = "bad"

{1:['good', 'bad']}

3, 
key = 2
value = "bad"

{1:['good', 'bad'], 2:['bad']}

然后我想从密钥中获取数组:

print $tags_hash{'1'};

Returns: ['good', 'bad']

2 个答案:

答案 0 :(得分:2)

一个扩展示例:

#!/usr/bin/perl

use strict;
use warnings;

my $hash = {}; # hash ref

#populate hash
push @{ $hash->{1} }, 'good';
push @{ $hash->{1} }, 'bad';
push @{ $hash->{2} }, 'bad';

my @keys = keys %{ $hash }; # get hash keys

foreach my $key (@keys) { # crawl through hash
  print "$key: ";
  my @list = @{$hash->{$key}}; # get list associate within this key
  foreach my $item (@list) { # iterate through items
    print "$item ";
  }
  print "\n";
}

输出:

1: good bad 
2: bad 

答案 1 :(得分:1)

因此hash元素的值为数组ref。完成后,您需要做的就是将值推送到数组上。

$hash{$key} //= [];
push @{ $hash{$key} }, $val;

或以下内容:

push @{ $hash{$key} //= [] }, $val;

或者,由于自动更新,只需以下内容:

push @{ $hash{$key} }, $val;

例如,

for (
   [ 1, 'good' ],
   [ 1, 'bad' ],
   [ 2, 'bad' ],
) {
   my ($key, $val) = @$_;
   push @{ $hash{$key} }, $val;
}