Bootstrap FreeKB - Perl (Scripting) - Append values to a reference hash
Perl (Scripting) - Append values to a reference hash

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 have the following reference hash. In this example, the foo key in the hash is empty.

my $hash = { 'foo' => '' };

 

Dumper can be used to display the structure of the hash.

use Data::Dumper;
print Dumper $hash;

 

Which should produce the following.

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

 

A value can be appended to the foo key, like this.

$hash->{foo} = "bar";

 

Dumper can be used to display the structure of the hash.

use Data::Dumper;
print Dumper $hash;

 

Now, the foo key contains a value of bar.

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

 

Here is how you would append a value to the reference hash where there are two (or more) keys, which means the hash is multidimensional.

$hash->{foo}->{bar} = "Hello World";

 

Dumper can be used to display the structure of the hash.

use Data::Dumper;
print Dumper $hash;

 

Now, the bar key is below the foo key (multidimensional), and the bar key contains a value of Hello World.

$VAR1 = {
           'foo' => {
                      'bar' => 'Hello World'
                    }
            };

 




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 93f3e9 in the box below so that we can be sure you are a human.