Question

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:

e.g. 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']
Was it helpful?

Solution

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 

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top