1. Home
  2. Computing & Technology
  3. Perl

Perl keys() function - Quick Tutorial
How to use the keys() function

From About.com

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:
name
phone
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";
}
More Perl Quick Tips
Explore Perl
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. Perl keys function reference - learn how to use Perl's keys() function in this quick tutorial.

©2009 About.com, a part of The New York Times Company.

All rights reserved.