
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 regular hash named %hash and the regular 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";
Special characters
Let's say the hash contains the forward slash character.
my %hash = ( '/' => 'bar' );
And you attempt to print the hash without wrapping the forward slash character in single quotes.
print "$hash{/} \n";
Should return something like this.
Search pattern not terminated at foo.pl line 8.
Certain special characters, such as the forward slash, must be wrapped in single quotes.
print "$hash{'/'} \n";
Variables
Variables can be used instead of strings.
my $key = "foo";
print "$hash{$key} \n";
Multidimensional
Let's say the hash is multidimensional.
my %hash = ( 'foo' => { 'bar' => 'Hello World' } );
Dumper should return the following.
$VAR1 = {
'foo' => {
'bar' => 'Hello World'
}
};
Here is how you would print the value of the "bar" key.
print "$hash{foo}->{bar} \n";
Did you find this article helpful?
If so, consider buying me a coffee over at