FreeKB - Perl (Scripting) Hash (grep keys)
Perl (Scripting) - Hash (grep keys)

In Perl, there are 3 different kinds of hashes.

  • A regular hash, which is defined by the % and ( ) characters - %hash = ( );
  • A reference hash, which is defined with the $ and { } characters = $hash = { };
  • A hash array, 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_key, id_key, department_key).

my %hash;
$hash{employee_key}   = "John Doe";
$hash{id_key}         = "123456";
$hash{department_key} = "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.



Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

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


Web design by yours truely - me, myself, and I   |   |