Perl keys Function

The Perl keys function can be used with hashes or arrays, in a list or a scalar context.

The syntax forms are:

keys %hash
keys @array

If you use it with a hash, this function returns:
  • a list with the hash keys – in a list context (this list can be used for further processing)
  • the number of the hash elements (key-value pairs) – in scalar context

Click Below to See the Best

Perl How-to Snippet Collection

and Save Hours of Surfing on Internet!

In the following example we’ll iterate through the list returned by the Perl keys function using a foreach loop:


use strict;
use warnings;

# initialize a hash with a few elements
my %hash = (father => 'John', mother => 'Alice', 
            son => 'Andrew', daughter => 'Mary');
# print the hash by using foreach and keys
print "The keys are: ";
foreach my $key (keys % hash) {
  print "$key ";
print "\n";

This code outputs:

The keys are: son daughter father mother

As you can notice, the keys are returned in a random order and not in the order we inserted them into the hash.

The counterpart of the keys function is the values function which in a list context returns the values of the hash. Even though the order of returning the elements is random, you can count on the same order if you call any of the each, keys or values function on the same hash.

Each hash and array used in your script has a unique internal iterator and calling the Perl keys function has as effect the resetting of this iterator.

Next, I’ll show you an example where the keys function is used in a scalar context:


use strict;
use warnings;

my %hash = ();
my $count = 1;

while (keys %hash < 10) {
  $hash{++$count} = $count * 2 - 1;  

foreach my $key ( sort {$a <=> $b} keys %hash){
  print "$hash{$key} "
print "\n";

If you run this code you’ll get as output:

1 3 5 7 9 11 13 15 17 19

First, the $count variable is set to 1.

As you can see, you’ll get as output the first ten odd numbers. What is interesting here is the while loop. The keys function is invoked here in a scalar context and it will return the number of the hash keys.

Inside the while loop we’ll add a (key, value) pair element to our %hash, until the hash has 10 elements, when the loop will end. The hash values are the first ten odd numbers.

To print the hash values a foreach loop is used. The hash values will be printed in an ascending numerical order of the keys using the sort and print functions.
Next, I’ll give you a few examples about how to use the Perl keys function with arrays. After my opinion with arrays this function is not very often used, but let’s see how it works:


use strict;
use warnings;

my @array = (1, 2, 3, 4);
$#array = 9;

print("The indices are: ", join(' ', keys @array), "\n");

This snippet will produce the following result:

The indices are: 0 1 2 3 4 5 6 7 8 9

In the above example, the @array is initialized with a few elements. Next, the @array is enlarged to ten elements by setting the last index of the array with 9. To print the indices of the array the print, join and keys function were used.

Finally, you can get the array size (the number of elements of an array) by using the Perl keys function in a scalar context, as you can see in the following code line:

my $size = keys @array;

As you can see, there are many ways to do a thing in Perl.

A-N-Y-O-N-E Can Learn and Master Perl!
And That Includes YOU!

Check these how-to tutorial eBooks (PDF format):

Table of Contents:

A Perl Script
Install Perl
Running Perl
Perl Data Types
Perl Variables
Perl Operators
Perl Lists
Perl Arrays
    Array Size
    Array Length
Perl Hashes
Perl Statements
    Perl if
    Perl unless
    Perl switch
    Perl while
    Perl do-while
    Perl until
    Perl do-until
    Perl for
    Perl foreach
Built-in Perl Functions
    Functions by Category
        String Functions
        Regular Expressions and Pattern Matching
        List Functions
        Array Functions
        Hash Functions
        Miscellaneous Functions
    Functions in alphabetical order
        keys (more)

return from Perl keys Function to Perl Basics

Would you like to create your own website like this one?
Hit the Alarm Clock!

Site Build It!