variables beginner

How to get all keys from a hash in Perl?

Question

How to get all keys from a hash in Perl?

In Perl, hashes are unordered collections of key-value pairs, and one common requirement is to retrieve all the keys stored in a hash. Perl provides a built-in function called keys to do just that.

Getting all keys from a hash

The keys function takes a hash as input and returns a list of all its keys. The keys are returned in no guaranteed order, as hashes are inherently unordered. You can capture these keys into an array or iterate over them directly.

Here’s the general syntax:


my @keys = keys %hash;

This code puts all keys of %hash into the array @keys. You can then manipulate or print the keys as needed.

Example: printing all keys from a hash


use strict;
use warnings;

# Define a hash with some fruit and colors
my %fruit_color = (
    apple  => 'red',
    banana => 'yellow',
    grape  => 'purple',
    lemon  => 'yellow',
);

# Get all keys in the hash
my @keys = keys %fruit_color;

print "All keys in the hash are:\n";
foreach my $key (@keys) {
    print "$key\n";
}

When you run this code, it will output all the fruit names (keys) in the hash. The order may vary because Perl hashes do not maintain insertion order by default.

Perl concepts and details

  • Sigils: Hash variables use the % sigil (example: %hash), but to get the list of keys, you just pass the hash (e.g. %hash) to keys. When storing keys in an array, you use @keys (array sigil).
  • Context: The keys function returns a list in list context (e.g., when assigned to an array). In scalar context, keys %hash returns the number of keys.
  • TMTOWTDI ("There's more than one way to do it"): You can iterate over keys directly without storing them first:
    
        foreach my $key (keys %hash) {
            print "$key\n";
        }
        

Common pitfalls

  • Remember that keys %hash does not return keys in any guaranteed order.
  • Don’t confuse hash slices (@hash{'key1', 'key2'}) with the keys function.
  • Using keys on a hash before it has any elements will return an empty list.
  • Accessing hash keys in scalar context gives a count, not the keys themselves.

Overall, the keys function is the idiomatic and simplest way to get all keys from a hash in Perl.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 6ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions