We don't bite newbies here... much | |
PerlMonks |
perlfunc:keysby gods (Initiate) |
on Aug 24, 1999 at 22:42 UTC ( [id://218]=perlfunc: print w/replies, xml ) | Need Help?? |
keysSee the current Perl documentation for keys. Here is our local, out-dated (pre-5.6) version: keys - retrieve list of indices from a hash
keys HASH
Returns a list consisting of all the keys of the named hash. (In a scalar context, returns the number of keys.) The keys are returned in an apparently random order, but it is the same order as either the values() or each() function produces (given that the hash has not been modified). As a side effect, it resets HASH's iterator. Here is yet another way to print your environment:
@keys = keys %ENV; @values = values %ENV; while ($#keys >= 0) { print pop(@keys), '=', pop(@values), "\n"; } or how about sorted by key:
foreach $key (sort(keys %ENV)) { print $key, '=', $ENV{$key}, "\n"; } To sort an array by value, you'll need to use a sort() 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 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
keys %hash = 200;
then |
|