Perl (Scripting) - Match keys in a hash using grep

by
Jeremy Canfield |
Updated: August 10 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 have the following hash. In this example, the hash has three keys (employee, id, department).
my %hash;
$hash{employee} = "John Doe";
$hash{id} = "123456";
$hash{department} = "Engineering";
grep can be used to only print certain keys. In this example, only id_key should be printed.
foreach my $key (keys %hash) {
print grep (/id/, $keys);
}
Which should return the following.
id
Did you find this article helpful?
If so, consider buying me a coffee over at