Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for existence of hash key creates key

Tags:

hash

perl

Given the following code

#!/usr/bin/perl

use Data::Dumper;

my %hash;
my @colos = qw(ac4 ch1 ir2 ird kr3);

foreach my $colo (@colos) {
    if(exists $hash{output}{$colo}) {
        print "$colo is in the hash\n";
    }
}

print Dumper(\%hash);

I have an empty hash that is created. I have an array with a few abbreviations in it. If I cycle through the array to see if these guys are in the hash, nothing is displayed to STDOUT which is expected but the $hash{output} is created for some reason. This does not make sense. All I am doing is an if exists. Where did I go wrong?

like image 908
gdanko Avatar asked Mar 20 '12 15:03

gdanko


1 Answers

exists looks for a hash element in a given hash. Your code is autogenerating the hash
%{ $hash{output} } and checking if a hash element with key $colo is existing in that hash.

Try the following:

if(exists $hash{output}{$colo}) {

changed to

if(exists $hash{output} and exists $hash{output}{$colo}) {

You can, of course, write a sub that is hiding that complexity from your code.

like image 190
Daniel Böhmer Avatar answered Nov 25 '22 10:11

Daniel Böhmer