Приглашаем посетить
Чуковский (chukovskiy.lit-info.ru)

Hash Odds and Ends

Previous Table of Contents Next

Hash Odds and Ends

Some operations on hashes aren't obvious if you're new to Perl. Because of the special nature of hashes, a couple of common operations require functions that aren't necessary for scalars and arrays.

Testing for Keys in a Hash

To test to see whether a key exists in a hash, for example, you might be tempted to try the following syntax:


if ( $Hash{keyval} ) {        # WRONG, in this case

    :

}


This example doesn't work, for a few reasons. First, this snippet doesn't test to see whether keyval is a key in a hash; it actually tests the value associated with the key keyval in the hash.

Does it work to test whether the key is defined, as in the following?


if ( defined $Hash{keyval} ) {    # WRONG, again in this case

    :

}


Again, this example doesn't quite work. This snippet still tests the data associated with the key keyval, and not whether the key exists. undef is a perfectly valid value to associate with a hash key, as in the following:


$Hash{keyval} = undef;


The preceding test of defined returns false because it doesn't test for the existence of a key in a hash; it tests the data associated with the key. So what's the right way? Perl has a special function just for this purpose; it's called exists. The exists function, shown here, tests for the presence of the hash key in the hash and returns true if it's there or false otherwise:


if ( exists $Hash{keyval} ) {    # RIGHT!

    :

}


Removing Keys from a Hash

The other operation that isn't obvious is removing a key from a hash. As you saw earlier, simply setting the hash element to undef doesn't work. To remove a single hash key, you can use the delete function, as follows:


delete $Hash{keyval};


To remove all the keys and values from a hash, simply reinitialize the hash to an empty list like this:


%Hash = ();


    Previous Table of Contents Next