Perl, check if pair exists in hash of hashes

In Perl, I have a hash of hashes created with a loop similar to the following

    my %HoH
    for my $i (1..10) {
      $HoH{$a}{$b} = $i; 
    }

$a and $b are variables that do have some value when the HoH gets filled in. After creating the HoH, how can I check if a particular pair ($c, $d) exists in the HoH? The following does not work

if (defined $HoH{$c}{$d}) {...}

because if $c does not exist in HoH already, it will be created as a key without a value.

Answers


use Data::Dumper;

my %HoH;

$HoH{A}{B} = 1;

if(exists $HoH{C} && exists $HoH{C}{D}) {
   print "exists\n";
}

print Dumper(\%HoH);

if(exists $HoH{C}{D}) {
   print "exists\n";
}

print Dumper(\%HoH);

Output:

$VAR1 = {
          'A' => {
                   'B' => 1
                 }
        };
$VAR1 = {
          'A' => {
                   'B' => 1
                 },
          'C' => {}
        };

Autovivification is causing the keys to be created. "exists" in my second example shows this so the first example checks both keys individually.


Writing

if (defined $HoH{$c}{$d}) {...}

will "work" insomuch as it will tell you whether or not $HoH{$c}{$d} has a defined value. The problem is that if $HoH{$c} doesn't already exist it will be created (with an appropriate value) so that $HoH{$c}{$d} can be tested. This process is called "autovivification." It's convenient when setting values, e.g.

my %hoh;
$hoh{a}{b} = 1; # Don't need to set '$hoh{a} = {}' first

but inconvenient when retrieving possibly non-existent values. I wish that Perl was smart enough to only perform autovivification for expressions used as lvalues and short-circuit to return undef for rvalues but, alas, it's not that magical. The autovivification pragma (available on CPAN) adds the functionality to do this.

To avoid autovivification you need to test the intermediate values first:

if (exists $HoH{$c} && defined $HoH{$c}{$d}) {
     ...
}

Need Your Help

Extend checkbox control on C#.net

c# .net-2.0

I want to extend checkbox control which can use on every form.

convert ExceptionDescribe to string

java c++ exception jni

I need to get the output of ExceptionDescribe() in JNI as string so I can write it afterwards in a file instead of writing it directly on command line. Is there any way or idea how to do that?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.