in reply to Best way check key availability

exists()

my $key = 'key01'; if (exists $hash{$key}) { print "$key is in hash"; }
If the values of in the hash can all be considered "true" (as in your example), then you could simplify this further to:
my $key = 'key01'; if ($hash{$key}) { print "$key is in hash"; }

Liz

Replies are listed 'Best First'.
Re: Re: Best way check key availability
by Anonymous Monk on Sep 11, 2003 at 17:09 UTC
    If the values of in the hash can all be considered "true" (as in your example), then you could simplify this further

    Not really.

    If the purpose of the quest is to find out if the key exists, then your second example will have an undesired side effect, because it will create 'key01' even if it didn't exist before. So the test is correct, but not its meaning, because key01 will be there, holding an undef value and ready to do havoc next time you use it.

      Nope. It won't. Observe:
      use strict; my %a; if ($a{'foo'}) {} print keys %a;

      According to your claim, this should print "foo". Well, it doesn't ;-)

      Liz

        I think our Anony Monk was thinking about multi-dimentinal hashes:

        my %a = ( foo => { }, bar => { }, ); if($a{baz}{key}) { }

        In this case, 'baz' is created in the first dimention. Since we're dealing with a single-dimentional hash, our Anony Monk was incorrect.

        ----
        I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
        -- Schemer

        Note: All code is untested, unless otherwise stated