Reputation: 16906
How do tell if a key exists in a has, when I have a reference to the hash? The following seemed simple and obvious (at my level of expertise) but prints out something other than expected:
%simple = (a => 8, b=> 9);
print 0+exists $simple{a}, 0+exists $simple{c}, "\n"; # prints 10
%href = \%simple;
print 0+exists $href{a}, 0+exists $href{c}, "\n"; # expect fail; bad syntax
print 0+exists $href->{a}, 0+exists $href->{c}, "\n"; # should work
print 0+exists ${$href}{a}, 0+exists ${$href}{c}, "\n"; # should work
print 0+exists $$href{a}, 0+exists $$href{c}, "\n"; # not sure
# see if attempt to ask about {c} accidently created it
print %simple, "\n";
This prints out
10
00
00
00
00
a8b9
I expect (being very optimistic):
10
10
10
10
10
a8b9
I don't expect all the ways I tried to work but at least one should. I've gone over perldoc, other SO questions, and Googling all over, and all I come up with is that the syntax I use in some of these lines should work.
Upvotes: 0
Views: 826
Reputation: 61369
The line
%href = \%simple;
doesn't do what you think it does; perl -w
(or use warnings;
) would give you a warning about an odd number of hash elements, which should be a sufficient hint as to what it tried to do (and, if you think about it, why your "bad syntax" isn't). Try
$href = \%simple;
Also, learn to use use warnings;
and use strict;
, and always use them.
Upvotes: 2