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 id 123456
Employee occupation Engineer
Employee status Active

 

Create an empty hash.

my %hash;

 

Create the keys and values.

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

 

Dumper can be used to print the hash.

print Dumper \%hash;

 

Which will produce the following.

$VAR1 = {
          'Employee' => [
                        '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 -> id -> 123456
Employee -> occupation -> Engineer
Employee -> status -> 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 433c1 in the box below so that we can be sure you are a human.




Comments