in reply to Re: strict "vars" mode for hash key literals?
in thread strict "vars" mode for hash key literals?

Wouldn't that be a runtime error? After all, the hash isn't even locked until lock_keys is executed at runtime.

Also, I think there is no performance penalty (except to the call to lock_keys), since I believe all lock_keys does is set the read-only flag on the hash, which is checked regardless of whether you've set lock_keys or not.

Replies are listed 'Best First'.
Re^3: strict "vars" mode for hash key literals?
by kennethk (Abbot) on Oct 18, 2016 at 17:32 UTC
    Yes, I should have clarified that it is a runtime error, but it is not a silent error. Thank you for bringing that up.

    You understand perlguts far better than I, but there is a measurable penalty for interacting with a hash with locked keys:

    #!/usr/bin/perl use strict; use warnings; use 5.10.0; use Hash::Util 'lock_keys'; use Benchmark 'cmpthese'; lock_keys my %hash1, qw/foo bar baz/; my %hash2; cmpthese(1e2, { 'lock' => sub { for (1 .. 1e5) {$hash1{foo}++;$hash1{bar}++;$ +hash1{baz}++;} }, 'no_lock' => sub { for (1 .. 1e5) {$hash2{foo}++;$hash2{bar}++;$ +hash2{baz}++;} }, });
    yields
    Rate lock no_lock lock 61.6/s -- -8% no_lock 66.8/s 8% --

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      ... measurable penalty ...

      Benchmark is tricky. When I looked at the output from your test, I thought "Heck, an 8% difference may be measurable, but it's sure not meaningful, not from Benchmark!"

      I ran your code several times and got a range of advantages for  'no_lock' of 10% - 79%. Discarding outliers and doing an eyeball average gave me an advantage of about 35%. (I won't reveal the actual values I got because I don't think they're really significant; a much larger sampling of benchmark comparisons would be needed to achieve some sort of statistical significance.)

      I then ran your code a few times with the  for (1 .. 1e5) { ... } loop limit set to 1e6. This runs several tens of seconds on my laptop. This produced a  'no_lock' advantage range of 4% - 25%, and an eyeball average sans outliers of about 15%.

      Multiple runs of Benchmark produce a set of measurements I think is meaningful, and a massaged advantage of roughly 15% to 35% is what I would consider significant. I wouldn't dispute this point. The (rather long-winded) point I want to make is that Benchmark comparisons should always be made repeatedly in order to be meaningful, and should always be taken with a grain of salt.


      Give a man a fish:  <%-{-{-{-<

Re^3: strict "vars" mode for hash key literals?
by hippo (Archbishop) on Oct 18, 2016 at 16:24 UTC

    Yes, it isn't trapped at compile time:

    $ perl '-mfeature=say' -cw 1174218.pl Name "main::var" used only once: possible typo at 1174218.pl line 7. 1174218.pl syntax OK