
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 = { };
Here is how you can create an empty reference hash.
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 = {};
Keys that contain no values (empty keys) can be created like this.
my $hash = { 'foo' => '', 'bar' => '' };
Or like this.
$hash->{foo} = undef;
$hash->{bar} = undef;
Or like this.
$hash->{foo} = '';
$hash->{bar} = '';
Dumper can be used to display the structure of the hash.
print Dumper $hash;
Which should return the following.
$VAR1 = {
'bar' => '',
'foo' => ''
};
Let's say you want to create a reference hash that has two (or more) keys, like this. In this example, the bar key is a child of the foo key.
'foo' {
'bar' => 'Hello World'
}
Here is how you can create the multidimensional keys and value.
my $hash = { 'foo' => { 'bar' => 'Hello World' } };
Or like this.
my $hash->{foo}->{bar} = "John Doe";
Dumper can be used to print the hash.
print Dumper \%hash;
Which will produce the following.
$VAR1 = {
'foo' => {
'bar' => 'Hello World'
}
};
Or to print the value of the bar key.
print $hash->{foo}->{bar};
Which will produce the following.
Hello World
Did you find this article helpful?
If so, consider buying me a coffee over at