icon Top 9 categories map      RocketAware > Perl >

keys HASH

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.



Home

Search Perl pages


Subjects

By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Math
Integer, Floating point, Matrix, Statistics, Boolean, ...

Processing
Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Communications
Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...

    
keys HASH
Returns a normal array 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 %hash will have at least 200 buckets allocated for it. 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).

Source: Perl builtin functions
Copyright: Larry Wall, et al.
Next: kill LIST

Previous: join EXPR,LIST



(Corrections, notes, and links courtesy of RocketAware.com)


[Overview Topics]

Up to: Data structures (In memory)




Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlfunc/keys.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments