home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Perl CookbookPerl CookbookSearch this book

5.3. Creating a Hash with Immutable Keys or Values

5.3.1. Problem

You'd like to have a hash whose keys or values can't be altered once set.

5.3.2. Solution

Use the appropriate functions from the standard Hash::Util module.

use Hash::Util qw{ lock_keys  unlock_keys
                   lock_value unlock_value
                   lock_hash  unlock_hash  };

To restrict access to keys already in the hash, so no new keys can be introduced:

lock_keys(%hash);                # restrict to current keys
lock_keys(%hash, @klist);        # restrict to keys from @klist

To forbid deletion of the key or modification of its value:

lock_value(%hash, $key);

To make all keys and their values read-only:

lock_hash(%hash);

5.3.3. Discussion

Suppose you're using a hash to implement a record (or an object) with some pre-determined set of keys, such as "NAME", "RANK", and "SERNO". You'd like to consider it an error to access any keys besides the ones initially in the hash, such as "ANME", a typo. Because Perl always creates hash elements on demand, this wouldn't be caught the way it would if you misspelled a variable name while under the use strict pragma.

The Hash::Util module's lock_keys function takes care of this for you. Once a hash is marked as having locked keys, you can't use any other keys than those. The keys need not yet be in the hash, and they may still be deleted if they are. But no new keys may be used.

Access to the values in those locked keys is not restricted by lock_keys. However, you may use the lock_value function to render a value in a hash read-only. That hash can also have its keys locked, but doesn't need to if the goal is just to have one or more values marked read-only.

If you want to lock down the entire hash, thereby restricting both its keys and its values, the lock_hash function will do.

5.3.4. See Also

The documentation for the Hash::Util module



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.