Search code examples
perlhashkeyundefinedautovivification

Perl defining undefined keys


The following code prints Key defined 3. Why is Perl defining the key ABC ? I was expecting all the three checks to be false.What am I doing incorrectly ?

#!/usr/bin/perl 
use warnings;
use strict;

my %Hash;

if(defined $Hash{'ABC'})
{
    printf("Key defined 1\n");
}

if(defined $Hash{'ABC'}{'Status'})
{
    printf("Key defined 2\n");
}

if(defined $Hash{'ABC'})
{
    printf("Key defined 3\n");
}

Solution

  • This $Hash{'ABC'}{'Status'} autovivifies the ABC key (see perldoc perlref and wikipedia):

    use warnings;
    use strict;
    use Data::Dumper;
    
    my %Hash;
    
    if(defined $Hash{'ABC'})
    {
        printf("Key defined 1\n");
    }
    print Dumper(\%Hash);
    
    if(defined $Hash{'ABC'}{'Status'})
    {
        printf("Key defined 2\n");
    }
    print Dumper(\%Hash);
    
    if(defined $Hash{'ABC'})
    {
        printf("Key defined 3\n");
    }
    print Dumper(\%Hash);
    
    __END__
    
    $VAR1 = {};
    $VAR1 = {
              'ABC' => {}
            };
    Key defined 3
    $VAR1 = {
              'ABC' => {}
            };
    

    See also Data::Diver and the autovivification pragma, which prevent autovivification.