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

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter ec5b60 in the box below so that we can be sure you are a human.