Search code examples
arraysperlperl-data-structures

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:

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

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