
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 = { };
In this example, the foo key in the hash is an array, as indicated by the [ ] characters. The foo key is empty (contains no values).
my %hash = ( 'foo' => [] );
You can count the elements.
my $count = @{$hash{foo}};
print "\$count = $count \n";
Which will return 0, since the foo key is empty.
$count = 0
Dumper can be used to display the structure of the hash.
use Data::Dumper;
print Dumper \%hash;
Which should produce the following.
$VAR1 = {
'foo' => []
};
Let's say you do this.
push @{$hash{foo}}, { 'name' => 'John Doe', 'department' => 'engineering' };
push @{$hash{foo}}, { 'name' => 'Jane Doe', 'department' => 'sales' };
Now, the foo key contains key value pairs.
$VAR1 = {
'foo' => [
{
'name' => 'John Doe',
'department' => 'engineering'
},
{
'name' => 'Jane Doe',
'department' => 'sales'
}
]
};
You can loop through the foo key to print the value associated with the key.
foreach my $foo (@{$hash{foo}}) {
print "$foo->{name} \n";
}
Which in this example will print the value of the name key.
John Doe
Jane Doe
Here is how you can remove all of the elements from the foo key in the hash so that the foo key contains no key value pairs.
%hash = ( 'foo' => [] );
You can count the elements in the foo key again.
my $count = @{$hash{foo}};
print "\$count = $count \n";
Which will return 0, since the foo key has been made empty again.
$count = 0
Dumper can be used to display the structure of the hash again.
use Data::Dumper;
print Dumper \%hash;
Which should now produce the following again since the foo key contains no key value pairs.
$VAR1 = {
'foo' => []
};
Did you find this article helpful?
If so, consider buying me a coffee over at