5.4. Hash Functions

This section lists some functions for hashes.

5.4.1. The keys Function

The keys(%hashname) function yields a list of all the current keys in the hash %hashname. In other words, it's like the odd-numbered (first, third, fifth, and so on) elements of the list returned by unwinding %hashname in an array context, and in fact, returns them in that order. If there are no elements to the hash, then keys returns an empty list.

For example, using the hash from the previous examples:

$fred{"aaa"} = "bbb";
$fred{234.5} = 456.7;
@list = keys(%fred); # @list gets ("aaa",234.5) or
                     # (234.5,"aaa")

As with all other built-in functions, the parentheses are optional: keys %fred is like keys(%fred).

foreach $key (keys (%fred)) { # once for each key of %fred
    print "at $key we have $fred{$key}\n"; # show key and value
}

This example also shows that individual hash elements can be interpolated into double-quoted strings. You cannot interpolate the entire hash, however.[3]

[3] Well, you can, using a slice, but we don't talk about slices here.

In a scalar context, the keys function gives the number of elements (key-value pairs) in the hash. For example, you can find out whether a hash is empty:

if (keys(%somehash)) { # if keys() not zero:
    ...; # array is non empty
}
# ... or ...
while (keys(%somehash) < 10) {
    ...; # keep looping while we have fewer than 10 elements
}

In fact, merely using %somehash in a scalar context will reveal whether the hash is empty or not:

if (%somehash ...

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.