Hash::Util's lock_keys

Robert Rothenberg robrwo at gmail.com
Wed Feb 19 15:54:16 GMT 2014


Interesting idea, but you have to export the key names. (On could also use
enums and an array, but then it starts to look more like C than Perl.)

I played around with something like this years ago,
https://metacpan.org/pod/Tie::InsideOut


On Wed, Feb 19, 2014 at 1:51 PM, Abigail <abigail at abigail.be> wrote:

> 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.
>
>
>
> Abigail
>
>
> [1]  This was one of the reasons for me to develop inside-out objects.
>


More information about the london.pm mailing list