Hack 87. Lock Down Your Hashes


Protect against typos in your hashes.

As much as the scalar is the fundamental data type in Perl, the hash is perhaps the most usefulexcept for one small flaw. Though use strict protects against embarrassing typos in variable names, it does nothing to protect against mistyping hash keys.

If you're fortunate enough to use Perl 5.8.0 or newer, you can protect yourself with locked hashes.

The Hack

Suppose you're working on code that needs to sling around several hashes and your coworkers keep mistyping key names.[3] Though things all look correct, it's difficult to catch and debug and it causes you plenty of problems.

[3] As if anyone would ever misspell "referrer."

Rather than searching the entire program's source code (and vetting the contents of all possible variables and configuration files and every place you could get a new hash key), lock the hash's keys:

use Test::More tests => 2; use Hash::Util 'lock_keys'; my %locked   = ( foo => 1, bar => 2 ); my %unlocked = ( foo => 1, bar => 2 ); lock_keys( %locked ); eval {   $locked{fool} = 1 }; eval { $unlocked{fool} = 1 }; is( keys %locked,  2, 'hash with locked keys should disallow unknown key' ); is( keys %unlocked, 3, '... but unlocked hash should not' );

Running the Hack

Anyone can add any keys and values to %unlocked, but trying to read from or write to a key not in the hash (in this case, fool) when you call lock_keys( ) will fail with the error:

Attempt to access disallowed key 'fool' in a restricted hash...

Run your test suite and check the line number of the error message to find the culprit. Fix. Repeat.

Note that you can still call exists without triggering the exception. Also, if your co-workers are particularly evil or at least actively malicious, they can call unlock_keys( ) before doing bad things. If this is the case, you have bigger problems than misspellingssuch as not having a comprehensive test suite.

Though this may seem like it solves some of the problems of using blessed hashes as the basis of objects, it has several limitations, especially that it still doesn't enforce any encapsulation. See instead "Turn Your Objects Inside Out" [Hack #43].




Perl Hacks
Perl Hacks: Tips & Tools for Programming, Debugging, and Surviving
ISBN: 0596526741
EAN: 2147483647
Year: 2004
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net