Hash Functions
Here are some functions for hashes.
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.
Here’s an 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
)
.
For example:
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.[45]
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: ...; # hash is non empty } # ... or ... while (keys(%somehash
) < 10) { ...; # keep looping while we have less than 10 elements }
In fact, merely using %somehash
in a
scalar context will reveal whether the hash is empty or not:
if (%somehash
) { # if true, then something's in it
# do something with it
}
The values Function
The ...
Get Learning Perl on Win32 Systems 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.