++ for restricted hashes. But as pointed by ikegami, they do not catch the exception at compile time.

There might be a source filter somewhere on CPAN that does what you want, if you're ok with using a source filter. Parsing the code for /[$](\w+)[{](\w+)[}]/ and making sure that $2 is a valid key for hash $1 would probably be easy and safe enough.

Otherwise, there's the solution of using constants. Either by using an array instead of the hash:

use strict; use warnings; use constant { FOO => 0, BAR => 1, BAZ => 2 }; $var = BAZ; my @array; say $array[FOO]; # OK say $array[BAH]; # Bareword "BAH" not allowed while "strict subs" in +use say $array[$var]; # OK
Or never allowing the bareword interpretation for a hash key by adding a + (there's no way to disable ALL barewords is there?)
use strict; use warnings; use constant { FOO => "foo", BAR => "bar", BAZ => "baz" }; my %hash; say $hash{+FOO}; # OK say $hash{+BAH}; # Bareword "BAH" not allowed while "strict subs" in +use say $hash{+shift} # Bonus


In reply to Re: strict "vars" mode for hash key literals? by Eily
in thread strict "vars" mode for hash key literals? by perlancar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.