develooper Front page | perl.perl5.porters | Postings from January 2017

Re: Should we consider locked hashes a failed experiment?

Thread Previous | Thread Next
From:
demerphq
Date:
January 30, 2017 19:47
Subject:
Re: Should we consider locked hashes a failed experiment?
Message ID:
CANgJU+WTiOTNAf2UeVneggK86WdTE4VCOgNvekvZrtp98AM9EQ@mail.gmail.com
On 30 January 2017 at 18:13, Dave Mitchell <davem@iabyn.com> wrote:
> On Sat, Jan 28, 2017 at 03:31:48PM +0100, demerphq wrote:
>> My experience with locked hashes is that as currently implemented they
>> are nearly useless.
>
> Their main advantage (as exposed by 'use fields') is that they check,
> at *compile* time, that you're not using an invalid key for an
> object, which has always been a big elephant in the room as regards
> Perl's idiosyncratic use of hashes as objects.
>
>     package Foo;
>
>     use fields qw(a b c);
>
>     sub new { bless { qw(a 1 b 2 c 3) } }
>
>     package main;
>
>     my Foo $Fr = Foo->new();
>
>     $Fr->{a} = 1; # ok
>     $Fr->{d} = 1; # compile-time error
>
> I'm not sure what checking is done at run time.

As far as I can tell none of the behavior demonstrated by your code is
implemented by restricted hashes; in fact your sub new{} overrode the
use of Hash::Util::lock_keys() in the constructor in fields.pm so your
code does not use restricted hashes at all.

An actual exception from restricted hash code would look like this:

use Hash::Util qw(lock_hash);
my %hash=(foo=>1,bar=>2);
lock_hash(%hash);
print $hash{blah};
__END__
Attempt to access disallowed key 'blah' in a restricted hash at ....

FWIW, I don't think I have ever seen anyone write

my Foo $foo= Foo->new();

in the wild. No doubt they do somewhere, but not in any code I have
looked at. And if you omit the "Foo" from "my Foo" (an easy mistake
IMO) then the compile time checks go away as well, and fields.pm
becomes completely run-time.

cheers
Yves





Yves
ps: Where can i read up on how this is working at an internals level?
-- 
perl -Mre=debug -e "/just|another|perl|hacker/"

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About