Movatterモバイル変換


[0]ホーム

URL:


functions /keys
(source,CPAN)
You are viewing the version of this documentation from Perl 5.8.1.View the latest version
#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 thevalues oreach 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".

Here is yet another way to print your environment:

    @keys = keys %ENV;    @values = values %ENV;    while (@keys) {print pop(@keys), '=', pop(@values), "\n";    }

or how about sorted by key:

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

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 asort function. Here's a descending numeric sort of a hash by its values:

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

As an lvaluekeys 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

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 = (), useundef %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 usingkeys in this way (but you needn't worry about doing this by accident, as trying has no effect).

See alsoeach,values andsort.

Perldoc Browser is maintained by Dan Book (DBOOK). Please contact him via theGitHub issue tracker oremail regarding any issues with the site itself, search, or rendering of documentation.

The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via thePerl issue tracker, themailing list, orIRC to report any issues with the contents or format of the documentation.


[8]ページ先頭

©2009-2025 Movatter.jp