Perl (Scripting) - Append keys to a hash that contains an array

by
Jeremy Canfield |
Updated: December 23 2022
| 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 a hash named %hash that will be used to store employees data. In this example, the employees key is an array, as indicated by the [ ] characters and the employees key is empty (contains to keys or values). Dumper can be used to display the structure of the hash.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %hash = ( 'employees' => [], 'manager' => [] );
print Dumper \%hash;
Which should produce the following.
$VAR1 = {
'employees' => [],
'managers' => []
};
Let's say you do this.
push @{$hash{employees}}, { 'name' => '', 'department' => '' };
push @{$hash{managers}}, { 'name' => '', 'department' => '' };
Now, the hash should look like this.
$VAR1 = {
'employees' => [
{
'name' => '',
'department' => ''
}
],
'managers' => [
{
'name' => '',
'department' => ''
}
]
};
You can loop through the hashes and use Dumper to print only the keys.
foreach my $employee (@{$hash{employees}}) {
foreach my $key ( %$employee) {
print "\$key = $key \n";
}
}
Which should return the following.
$key = name
$key = department
Did you find this article helpful?
If so, consider buying me a coffee over at