FreeKB - Multidimensional Hash Array in Perl
Multidimensional Hash Array in Perl

Home > Search


If you are not familiar with a hash in Perl, check out our getting started article.

Let's say you want to create a hash that has two (or more) keys, like this.

First Key Second Key Value
Employee Jeremy 123456
Employee Jeremy Engineer
Employee Jeremy Active

 

Create an empty hash.

my %hash;

 

Then, create the multidimensional keys and values.

push (@{$hash{"Employee"}->{"Jeremy"}}, "123456");
push (@{$hash{"Employee"}->{"Jeremy"}}, "Engineer");
push (@{$hash{"Employee"}->{"Jeremy"}}, "Active");

 

Dumper can be used to print the hash.

print Dumper \%hash;

 

Which will produce the following.

$VAR1 = {
          'Jeremy' => [
                        'id' => '123456',
                        'occupation' => 'Engineer',
                        'status' => 'Active'
                      ]
        };

 

And you can loop through the hash.

foreach my $key1 (keys %hash) {
  foreach my $key2 (keys %{$hash{$key1}}) {
    foreach my $value (@{$hash{$key1}->{$key2}}) {
        print "$key1 -> $key2 -> $value\n";
    }
  }
}

 

Which will produce the following.

Employee -> Jeremy -> 123456
Employee -> Jeremy -> Engineer
Employee -> Jeremy -> Active

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 802ac in the box below so that we can be sure you are a human.




Comments