Perl (Scripting) - Print values in a reference hash

by
Jeremy Canfield |
Updated: May 23 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 a reference hash named $hash and the reference hash contains a single key with a single value.
my $hash = { 'foo' => 'bar' };
Dumper can be used to display the structure of the hash.
use Data::Dumper;
print Dumper $hash;
Which should produce the following.
$VAR1 = {
'foo' => 'bar'
};
Here is how to print the value associated with department_key.
print "$hash->{foo} \n";
Which should print the following.
bar
White space
Let's say the hash key contains white space. In this example, there is a single white space in "foo bar".
my $hash = { 'foo bar' => 'Hello World' };
When there is white space, the key must be wrapped in single quotes.
print "$hash->{'foo bar'} \n";
Did you find this article helpful?
If so, consider buying me a coffee over at