++ 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:
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 => 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
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |