Perl's keys() function

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";
}

你可能感兴趣的:(Perl's keys() function)