Hash::Util's lock_keys

Abigail abigail at abigail.be
Wed Feb 19 13:51:09 GMT 2014

On Wed, Feb 19, 2014 at 01:26:33PM +0000, Smylers wrote:
> Robert Rothenberg writes:
> > At $work, we're having a debate about using restricted hashes
> > 
> >   https://metacpan.org/pod/Hash::Util#Restricted-hashes
> Given that we use strict to prevent typos in variable names, this seems
> like the equivalent technique for when a bunch of variables are grouped
> together in a hash, so I'm surprised that it isn't used widely.

I've been wondering about how easily people resort to storing data in
hashes, using string literals as keys, while they cry foul if they ever
saw a program not using strict. Specially when it comes to traditional
Perl objects, who store their entire state in a hash, and none in a
lexical variable. [1]

Even without strict, typos in variables at least warn (assuming warnings
are on), while typos in string literals at best give you a run time
error or warning.

If you want to use named parameters, yet want to protect yourself
from typos, put the names in lexical variables:

    use strict;
    use warnings;

    my $NAME   = "name";
    my $AGE    = "age";
    my $COLOUR = "colour";

    sub some_method {
        my ($self, %args) = @_;

        printf "Name is %s; age is %d\n" => $args {$NAME}, $arg {$AGE};


    $object -> some_method ($NAME => "...", $AGE => ..., $COLOUR => "...");

And if you typo $COLOUR as $COLOR you get a *compile time* error, and
you don't have to waste runtime cycles to find your typos.


[1]  This was one of the reasons for me to develop inside-out objects.

More information about the london.pm mailing list