Bootstrap FreeKB - Perl (Scripting) - Define hash that contains an array
Perl (Scripting) - Define hash that contains an array

Updated:   |  Perl (Scripting) articles

In Perl, there are 2 different kinds of hashes.

  • A hash, which is defined by the % and ( ) characters - %hash = ( );
  • A reference hash, which is defined with the $ and { } characters - $hash = { };

 

Let's say you do the following. In this example, the name of the hash is %hash and the hash contains the foo key. The foo key is an empty array, as indicated by the [ ] characters.

my %hash = ( 'foo' => [] );

 

You could use Dumper to display the structure.

use Data::Dumper;
print Dumper \%hash;

 

The foo key is empty.

$VAR1 = {
          'foo' => []
        };

 


Multiple arrays

Let's say you do this.

my %hash = ( 'foo' => [], 'bar' => [] );

 

Now the hash contains two empty arrays.

$VAR1 = {
          'foo' => [],
          'bar' => []
        };

 


Let's say you do the following. In this example, the name of the hash is %hash and the hash contains the foo key. The foo key is an empty array, as indicated by the [ ] characters.

push @{$hash{primary}}, { 'foo' => [] };

 

Now the hash contains two arrays, the primary key array and the foo key array, where the foo key array is a child of the primary key array, meaning the hash is multidimensional. The foo key array is empty. However, the primary key array is not empty, since the primary key array contains the foo key array.

$VAR1 = {
          'primary' => [ 
                         { 
                           'foo' => []
                          }
                        ]
        };

 

Let's say you do this.

push @{$hash{primary}}, { 'foo' => { 'bar' => [] } };

 

Now Dumper should return the following.

$VAR1 = {
          'primary' => [ 
                         {
                           'foo' => {
                                      'bar' => []
                                    }
                          }
                        ]
        };

 


Don't do this

Let's say you do this.

push @{$hash{foo}}, "bar";

 

Now the foo key array contains a value. The value is bar.  This is outside of the scope of creating an empty array. Instead, this is how you append values to an array.

$VAR1 = {
          'foo' => [ 
                      'bar'
                   ]
        };

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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