Cheap web site hosting service by Active-Venture.com
  

 Back to Index

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). 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) {
	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 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 %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.

 

  

 

Domain registration - Domain registration service and cheap domain transfer
 

Cheap domain name: Register domain name -
Register domain name services from just
$8.95/year only
 

Register domain name search -
Register domain or buy domain name registration and cheap domain transfer at low, affordable price.

© 2002-2004 Active-Venture.com Web Site Hosting Service

 

[ All parts should go together without forcing. You must remember that the parts you are reassembling were disassembled by you. Therefore, if you can't get them together again, there must be a reason. By all means, do not use a hammer.   ]

 

 
 
 

Disclaimer: This documentation is provided only for the benefits of our web hosting customers.
For authoritative source of the documentation, please refer to http://www.perldoc.com