Re: Option to warn/die on fetch with invalid hash key?
[email protected] (Sam Kington)
| Newsgroups | perl.perl5.porters |
|---|---|
| Message-ID | <[email protected]> |
On 27 Dec 2025, at 01:52, Jim Avera <[email protected]> wrote: > Has there been past discussion of how (or whether) to allow warn/die if a non-existent hash key is used for a fetch? > […] > > For motivation, see https://stackoverflow.com/questions/3740833/how-can-i-make-perl-die-when-reading-but-not-writing-to-non-existing-keys-in-d Schwern’s answer mentions Hash::Util, which appears to do what you want? $ perl -E 'use Hash::Util qw(lock_keys); my %stuff = (foo => "stuff", bar => "more stuff"); say "Going to autovivify baz as $stuff{baz}"; lock_keys(%stuff); say "Trying $stuff{bletch} will now fail"' Going to autovivify baz as Attempt to access disallowed key 'bletch' in a restricted hash at -e line 1. I’m sure there are performance implications of doing this, though. For when you’re looking at the problem from a different angle, have a look at PerlX::Maybe <https://metacpan.org/pod/PerlX::Maybe>. Sam -- Website: https://www.illuminated.co.uk/