1

I have a problem, when I try to find if a entry exists in my Hash of Hash and if it don't exists, Perl create me this entry. Exemple of my code :

use warnings;
use strict;

my %hash;

$hash{'key1'}{'subkey1'} = "value1";

if ( defined($hash{'key2'}{'subkey2'}) ) {
    print "Here\n";
}

print keys %hash;

This code return :

key1key2

What is the best way to catch if this entry exists AND DONT add this in the Hash ? I have try with "exists" "defined" and it's a same thing.

Thank's for your support. And sorry for my English.

1 Answers1

4

You must first test for key2 before you can test for subkey2

if (defined($hash{'key2'}) && defined($hash{'key2'}{'subkey2'}) ) {
    print "Here\n";
}

Otherwise, Perl creates $hash{'key2'} in order to check for subkey2.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • 2
    Or just drop in the [autovivification](http://search.cpan.org/~vpit/autovivification/lib/autovivification.pm) module and include the `no autovivification;` pragma. – Kenosis Nov 19 '13 at 19:08