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