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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With