nikmit has asked for the wisdom of the Perl Monks concerning the following question:
Dear monks,
I came across this behaviour in perl which I find unintuitive, was wondering what the use case scenario for it is or whether I have done something wrong to bring it about...
I had a statement checking for the existence of data like so return 0 unless keys %{$hashref->{$key}} and I failed to realise that $key may not always exist.
I would have expected to see an error if $href->{$key} is undefined and therefore not a reference, but instead $key was just added to the hash.
Example:
#!/usr/bin/perl -w #perl-5.22.3 use strict; my $href = { cat => {milk => 1}, dog => {bone => 1} }; if (keys %{$href->{cow}}) { print "noop\n"; } else { if (exists $href->{cow}) { print "holy cow\n"; } else { print "no cow\n"; } }
This prints 'holy cow'
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: keys %{$hash->{$href}} adds $href to the hash if it doesnt exist?
by Discipulus (Canon) on Nov 17, 2017 at 09:32 UTC | |
by 1nickt (Canon) on Nov 17, 2017 at 13:54 UTC | |
by nikmit (Sexton) on Nov 17, 2017 at 10:15 UTC | |
|
Re: keys %{$hash->{$href}} adds $href to the hash if it doesnt exist?
by haukex (Archbishop) on Nov 17, 2017 at 09:42 UTC | |
|
Re: keys %{$hash->{$href}} adds $href to the hash if it doesnt exist?
by Eily (Monsignor) on Nov 17, 2017 at 10:01 UTC |