简体   繁体   中英

perl hash with array

I did same hash like this:

my %tags_hash;

Then I iterate some map and add value into @tags_hash:

if (@tagslist) {

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


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


        }}

But I would like to have has with array, so when key exists then add value to array. Something like this:

eg of iterations

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

And then I want to get array from the key:

print $tags_hash{'1'};

Returns: ['good', 'bad']

An extended example:

#!/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";
}

output:

1: good bad 
2: bad 

So the value of the hash element to be an array ref. Once you have that, all you need to do is push the value onto the array.

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

Or the following:

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

Or, thanks to autovivification, just the following:

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

For example,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM