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 of the keyval key in the hash. Does it work to test if the key is defined, as in the following?

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

Again, this example doesn't quite work. ...

Get Sams Teach Yourself Perl in 24 Hours now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.