1. Computing

Perl keys() function - Quick Tutorial

How to use the keys() function


 keys HASH 
Perl's keys() function is used to iterate (loop) through the the keys of a HASH. The keys are returned as a list (array).
 %contact = ('name' => 'Bob', 'phone' => '111-111-1111');
 foreach $key (keys %contact) {
   print "$key\n";
In the above example, we start with a simple hash of our contact Bob and his phone number. The keys function takes this regular hash as input, and is couched in a foreach loop. Here is the each function standing on it's own:
 $key (keys %contact) 
Every time the keys function is called, it grabs a key out of the hash and puts it in the $key string. When couched in the foreach statement it will loop through each element of the hash and pass the keys off to the print statement. The output of the program will be:
There are a couple of things to keep in mind when using the keys function. Because of the way Perl works with hashes, the elements will be returned in random order. Also, the keys function does not remove the elements from the hash - the hash is unaffected by the looping process.
So let's say that you want to sort your hash by the keys as you're looping through them. It's a simple matter of setting the keys function inside a sort function like so:
 %contact = ('name' => 'Bob', 'phone' => '111-111-1111');
 foreach $key (sort(keys %contact)) {
   print "$key\n";
  1. About.com
  2. Computing
  3. Perl
  4. Programming Perl
  5. How to Use Perl's Keys() Function - Tutorial

©2014 About.com. All rights reserved.