
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 = { };
The first step in creating a hash that contains an array is to define a hash or define a reference hash that has at least one key that contains an array.
Hash
Here is how you would define an empty hash named %hash where the foo key contains an array. The [ ] characters are used to set the foo key as an array.
my %hash = ( 'foo' => [] );
Or like this.
my %hash;
push @{$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' => []
};
Reference Hash
Here is how you would define an empty reference hash named $hash where the foo key contains an array. The [ ] characters are used to set the foo key as an array.
my $hash = { 'foo' => [] };
Or like this.
my $hash;
push @{$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' => []
};
Now you can append values to the hash array.
Did you find this article helpful?
If so, consider buying me a coffee over at