Question

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");
}
Était-ce utile?

La 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.

Autres conseils

$Hash{'ABC'}{'Status'}

is short for

$Hash{'ABC'}->{'Status'}

What you have there is a dereference. When a variable being dereferenced is undefined, autovivification kicks in to create the appropriate type of variable. This makes the above equivalent to

( $Hash{'ABC'} //= {} )->{'Status'}

You can avoid autovivification by avoiding dereferencing something undefined

if ($Hash{'ABC'} && defined $Hash{'ABC'}{'Status'})

Or you can use no autovivification;

no autovivification;
if (defined $Hash{'ABC'}{'Status'})
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top