FreeKB - Multidimensional Hash in Perl
Multidimensional Hash 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
Jeremy ID 123456
Jeremy Occupation Engineer
Jeremy Status Active

 

Create an empty hash.

my %hash;

 

Then, create the multidimensional keys and values.

$hash{"Jeremy"}{"id"}         = "123456";
$hash{"Jeremy"}{"occupation"} = "Engineer";
$hash{"Jeremy"}{"status"}     = "Active";

 

Or even better in my opinion, use -> to make it easier to read, like this.

$hash{"Jeremy"}->{"id"}         = "123456";
$hash{"Jeremy"}->{"occupation"} = "Engineer";
$hash{"Jeremy"}->{"status"}     = "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.

Jeremy -> id-> 123456
Jeremy -> occupation -> Engineer
Jeremy -> 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 27776 in the box below so that we can be sure you are a human.




Comments