Perl (Scripting) - Append values to a hash

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 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 (Hello World) to multidimensional keys, where the "bar" key is below the "foo" key.

$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 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

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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |