I updated my post with some more test cases. defined and exists behave similarly in regards to generating intermediate keys in the process of doing their work. I show an example of how to prevent this below.
I don't know if this helps or not, but checking for defined vs or exists can generate hash entries.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %hash = ('key' => 'value');
print Dumper \%hash;
#prints:
#$VAR1 = {
# 'key' => 'value'
# };
print "defined\n" if defined $hash{abc}{xyz}; # will create new keys
print "defined\n" if defined ($hash{x}) and defined ($hash{x}{y}); # a
+dded: won't create new keys
print "exists\n" if exists ($hash{x}) and exists($hash{x}{y}); # a
+dded: won't create new keys
print "exists\n" if exists $hash{x1}{x2}; # added: will create new
+keys
print "defined\n" if defined $hash{x3}; # added: no new key
print Dumper \%hash;
__END__
#prints:
# The "abc" key is created due to the check for defined of 2nd dimensi
+on
# exists will also create new intermediate keys
$VAR1 = {
'key' => 'value',
'abc' => {},
'x1' => {}
};
Sometimes you have to check at each level if the hash "dimension" exists. A check for "defined" or "exists" can generate automatic dimensions.
Sometimes you have to you have to check whether some hash key exists at all before checking what its value is (defined or not).
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|