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.

The
values(
%hashname
)
function returns a list of all the current values of the
%hashname
, in the same order as the keys returned by the
keys(
%hashname
)
function. As always, the
parentheses are optional. For example:

To
iterate over (that is, examine every element of) an entire hash, use
keys
, looking up each returned key to get the corresponding value. Although this method is frequently used, a more efficient way is to use
each(
%hashname
)
, which returns a key-value pair as a two-element list. On each evaluation of this function for the same hash, the next successive key-value pair is returned until all the elements have been accessed. When there are no more pairs,
each
returns an empty list.

So, for example, to step through the
%lastname
hash from the previous example, do something like this:

while (($first,$last) = each(%lastname)) {
print "The last name of $first is $last\n";
}

Assigning a new value to the entire hash resets the
each
function to the beginning. Adding or deleting elements of the hash is quite likely to confuse
each
(and possibly you as well).

So far, with what you know, you can add elements to a hash, but you cannot remove them (other than by assigning a new value to the entire hash). Perl provides the
delete
function to
remove hash elements. The operand of
delete
is a hash reference, just as if you were merely looking at a particular value. Perl removes the key-value pair from the hash. For example: