Thursday, August 8, 2013

Multi-Dimensional Hashes in Perl

Introduction To Hashes

Perl hashes are data types that allow you to associate data to a key. For example, a hash can store article titles with the date of publication as the key:

%hash = (20030227 => 'Multi-dimensional hashes',
         20030113 => 'Introduction to mod_perl',
         20021201 => 'The CPAN Module'

This is a one-dimensional hash.

Two-Dimensional Hash

You can however, create multi-dimensional hashes depending on your need. As in multi-dimensional arrays, multi-dimensional hashes are created using references. The references point to hashes. 

In our example, if we want to add say, author to the information, we cannot just add it to the content of the hash item. The hash item is a scalar so it contains only one information. If we want two information associated with a key, we can have these information in a hash:

%info = (title=> 'Multi-dimensional hashes',     
         author=> 'Philip Yuson'

We can then refer to this hash in the first hash item:

%hash2 = (20030227 => \%info);

When we do this, the data in $hash2{20030227} contains the reference to the %info hash. To access the title of that article, we can do this the long way:

$ref = $hash2{20030227}; # set $ref to the 
                         # reference pointing to 
                         # %info
       $ref->{title}; # get the data on the 
                         # title item of the %info hash.

We can shorten this to:
$hash2{20030227}->{title}; #

In this case, we remove the intermediate step of saving the reference to %info to the $ref variable. Perl also allows you to remove the pointer ->


In the example above, we have only one key. What if you want to set more than one keys? You can do this
    %info1 = (title=> 'Multi-dimensional hashes', 
              author=>'Philip Yuson'); 
%info2 = (title=> 'Introduction to mod_perl',
                        author=>'Philip Yuson'); 
%info3 = (title=>'The CPAN Module',
          author=>'Philip Yuson'); 
%hash3 = (20030227 =>\%info1, 

This is a bit awkward, so to simplify this:

%hash3 = ( 20030227 => {    title=> 'Multi-dimensional hashes',
                           author=>'Philip Yuson' },
                20030113 => {    title=> 'Introduction to mod_perl',
                          author=>'Philip Yuson' },
                20021201 => {    title=> 'The CPAN Module',
                       author=>'Philip Yuson' }

Multi-Dimensional Hashes

Based on the discussion, multi-dimensional hashes are made up of hashes that refer to hashes that refer to hashes.

No comments:

Post a Comment