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

Greetings:
I have contructed an array of hashes iteratively like so:
while(<DATA>){ ($key,$value)=split; push(@$myhash{$key}},$value); }
Twice, in following code I test for the presence of a key in this hash. I notice that the second time i perform the test, the script always observes the key exists. I am wondering if I am inadvertently defining a key in my first check? The check follows...It is identical each time performed:
if($myhash{$key)){ do something... }
Does this inadvertently define a key? If so, is there an easier, more accurate way?
Thanks for your help,
Jason

Replies are listed 'Best First'.
Re: Presence of Key in Hash of Arrays
by dpuu (Chaplain) on Aug 02, 2002 at 20:14 UTC
    Try:

    if (exists $myhash{$key}) { ... }

    This will avoid the "autovivication" of the hash element. However, I'm a bit confused: Your check might create the element, but it would give it an undefined value. So the next time you perform your check you should get the same value. --Dave

Re: Presence of Key in Hash of Arrays
by DamnDirtyApe (Curate) on Aug 02, 2002 at 20:41 UTC

    I tried to recreate your results, but the following code does not behave as you described:

    #! perl use strict ; use warnings ; $|++ ; my %myhash = () ; while ( <DATA> ) { my ( $key, $value ) = split ; push( @{ $myhash{ $key } }, $value ) ; } for my $key ( qw/ ni perch shrubbery / ) { if ( $myhash{ $key } ) { print "Found $key on pass 1.\n" ; } } for my $key ( qw/ ni perch shrubbery / ) { if ( $myhash{ $key } ) { print "Found $key on pass 2.\n" ; } } __DATA__ foo 1 bar 2 zoot 3 perl 4

    Could you post some working code that produces the results you mentioned?


    _______________
    D a m n D i r t y A p e
    Home Node | Email
Re: Presence of Key in Hash of Arrays
by insensate (Hermit) on Aug 02, 2002 at 20:12 UTC
    Sorry...let me restate 2 lines: In the first block:
    push(@{$myhash{$key}},$value);
    In the second:
    if($myhash{$key}){
    Thanks, Jason
Re: Presence of Key in Hash of Arrays
by tosh (Scribe) on Aug 02, 2002 at 22:31 UTC
    Yes this does define a key, it made me very very VERY angry when I finally tracked down my errors to this.

    exists might work, I've never tried it, I just had to wuss-out and check for a value not just existence, although I'm sure there's a better way.

    Tosh