Perl (Scripting) - Loop through key value pairs in an array in a hash

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 contains employees, and the employees key is an array, as indicated by the [ ] characters. Dumper can be used to display the structure of the hash.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %hash = ( 'employees' => [ { 'name' => 'John Doe', 'role' => 'Engineer' }, { 'name' => 'Jane Doe', 'role' => 'Sales' } ] );
print Dumper \%hash;
Which should return something like this.
$VAR1 = {
'employees' => [
{
'name' => 'John Doe',
'role' => 'Engineer'
},
{
'name' => 'Jane Doe',
'role' => 'Sales'
}
]
};
You can loop through the foo key to print the value associated with the key.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %hash = ( 'employees' => [ { 'name' => 'John Doe', 'role' => 'Engineer' }, { 'name' => 'Jane Doe', 'role' => 'Sales' } ] );
foreach my $employee (@{$hash{employees}}) {
print "$employee->{name} \n";
print "$employee->{role} \n";
}
Which should return the following.
John Doe
Engineer
Jane Doe
Sales
Did you find this article helpful?
If so, consider buying me a coffee over at