Perl (Scripting) - Append values to a hash

by
Jeremy Canfield |
Updated: August 11 2022
| 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 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