Perl (Scripting) - Append key value pairs to a hash

by
Jeremy Canfield |
Updated: May 12 2023
| 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, %hash is empty (no keys, no values).
my %hash;
Dumper can be used to display the structure of the hash.
use Data::Dumper;
print Dumper \%hash;
Which should produce the following.
$VAR1 = {};
Here is how you can append key value pairs to the hash.
$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'
};
Let's say you do this.
$hash{foo} = "hello";
$hash{foo} = "world";
In this scenario, the foo key will contain world. This overwrites the value in the foo key.
$VAR1 = {
'foo' => 'world'
};
One option might be to use different keys.
$hash{foo} = "hello";
$hash{bar} = "world";
Which should produce the following.
$VAR1 = {
'bar' => 'world',
'foo' => 'hello'
};
Did you find this article helpful?
If so, consider buying me a coffee over at