digirent has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to have an error trap when I reference an undefined hash key? And if yes how do I do that?
for instance: if($record->{typo_hashkey} eq "value") { .. actions } else { ... other actions }
What I would like during the debugging phase is that the program dies or has an error trap when the "typo_hashkey" does not exist.
This would save a lot of debugging time...

Thank in advance, Greetings Matthieu

Replies are listed 'Best First'.
Re: errortrapping/debugging typos when using undefined Hash keys
by roboticus (Chancellor) on Feb 24, 2011 at 11:01 UTC

    digirent:

    You may find Hash::Util useful. By locking the keys of the hash, you'll get an error if you try to reference keys that don't exist:

    $ cat hash_lock_keys.pl #!/usr/bin/perl use strict; use warnings; use Hash::Util qw(lock_keys); my %f = (alpha=>1, beta=>2, gamma=>3); lock_keys(%f); if ($f{apple} == 4) { print "Eh?\n"; } $ perl hash_lock_keys.pl Attempt to access disallowed key 'apple' in a restricted hash at hash_ +lock_keys.pl line 9.

    You can unlock the hash when you want to change it. The module has several other interesting-looking subroutines that you may find useful.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: errortrapping/debugging typos when using undefined Hash keys
by moritz (Cardinal) on Feb 24, 2011 at 10:55 UTC
      Thanks, I think the fields tip should do the trick! Greetings Matthieu
Re: errortrapping/debugging typos when using undefined Hash keys
by jwkrahn (Abbot) on Feb 24, 2011 at 10:45 UTC

    You probably want to use the exists function.

    And a hash key cannot be undefined, only a hash value can be.

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: errortrapping/debugging typos when using undefined Hash keys
by BrowserUk (Patriarch) on Feb 24, 2011 at 11:13 UTC

    A simple tied hash definition would help:

    #! perl -slw use strict; use 5.010; { package debughash; require Tie::Hash; use Carp qw[ croak ]; our @ISA = qw(Tie::Hash); sub TIEHASH { bless {}, $_[0]; } sub FETCH { croak 'Non-existent key' unless exists $_[0]{ $_[1 ] }; return $_[0]{ $_[1 ] }; } sub STORE { return $_[0]{ $_[1 ] } = $_[2]; } } use constant DEBUG => 1; my %hash; tie %hash, 'debughash' if DEBUG; $hash{ 'exists' } = 1; say $hash{ 'exists' }; say $hash{ 'nonexistant' }; __END__ C:\test>junk51 Non-existent key at C:\test\junk51.pl line 32

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.