Skip to Content
Perl Hacks
book

Perl Hacks

by Chromatic, Damian Conway, Curtis Ovid Poe, Curtis (Ovid) Poe
May 2006
Beginner
298 pages
6h 51m
English
O'Reilly Media, Inc.
Content preview from Perl Hacks

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 useful—except 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.

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl Debugged

Perl Debugged

Peter Scott, Ed Wright
Perl 6 Deep Dive

Perl 6 Deep Dive

Andrew Shitov
Learning Perl 6

Learning Perl 6

brian d foy
Perl by Example

Perl by Example

Ellie Quigley

Publisher Resources

ISBN: 0596526741Supplemental ContentErrata Page