【问题标题】:perl hash with arrayperl 哈希与数组
【发布时间】:2014-05-12 07:13:52
【问题描述】:

我做了同样的哈希:

my %tags_hash;

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

if (@tagslist) {

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


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


        }}

但我想拥有数组,所以当键存在时,将值添加到数组。 像这样的:

例如迭代次数

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']

【问题讨论】:

    标签: arrays perl perl-data-structures


    【解决方案1】:

    一个扩展的例子:

    #!/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:虽然最后 7 行可以简化为 print "$_: " . join (" ", @{$hash-&gt;{$_}}) ."\n" foreach (keys %$hash);
    • @jaypal 好主意,但如果与我的建议相比,我认为输出可能有点复杂。实际上所需的输出格式为:{1:['good', 'bad'], 2:['bad']},因此使用join function 处理这种格式有点棘手。
    【解决方案2】:

    所以哈希元素的值是一个数组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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 2020-07-19
      • 2011-07-02
      • 2012-08-22
      • 2012-06-12
      • 2012-07-22
      • 1970-01-01
      相关资源
      最近更新 更多