Modules

  • ABCDE
  • FGHIL
  • MNOPS
  • TUX

Tools

keys

Perl 5 version 10.1 documentation
Recently read

keys

  • keys HASH

    Returns a list consisting of all the keys of the named hash. (In scalar context, returns the number of keys.)

    The keys are returned in an apparently random order. The actual random order is subject to change in future versions of perl, but it is guaranteed to be the same order as either the values or each function produces (given that the hash has not been modified). Since Perl 5.8.1 the ordering is different even between different runs of Perl for security reasons (see Algorithmic Complexity Attacks in perlsec).

    As a side effect, calling keys() resets the HASH's internal iterator (see each). In particular, calling keys() in void context resets the iterator with no other overhead.

    Here is yet another way to print your environment:

    1. @keys = keys %ENV;
    2. @values = values %ENV;
    3. while (@keys) {
    4. print pop(@keys), '=', pop(@values), "\n";
    5. }

    or how about sorted by key:

    1. foreach $key (sort(keys %ENV)) {
    2. print $key, '=', $ENV{$key}, "\n";
    3. }

    The returned values are copies of the original keys in the hash, so modifying them will not affect the original hash. Compare values.

    To sort a hash by value, you'll need to use a sort function. Here's a descending numeric sort of a hash by its values:

    1. foreach $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) {
    2. printf "%4d %s\n", $hash{$key}, $key;
    3. }

    As an lvalue keys allows you to increase the number of hash buckets allocated for the given hash. This can gain you a measure of efficiency if you know the hash is going to get big. (This is similar to pre-extending an array by assigning a larger number to $#array.) If you say

    1. keys %hash = 200;

    then %hash will have at least 200 buckets allocated for it--256 of them, in fact, since it rounds up to the next power of two. These buckets will be retained even if you do %hash = () , use undef %hash if you want to free the storage while %hash is still in scope. You can't shrink the number of buckets allocated for the hash using keys in this way (but you needn't worry about doing this by accident, as trying has no effect).

    See also each, values and sort.