Monks, your responses to others have been very helpful to me for many years. Now however it is time to post my own question.
I am creating a multi-dimensional hash and then printing a non-existent key in that hash. Curiously (at least to me), that "print" is actually altering the hash, adding an invalid (for lack of a better word) key.
#!/usr/bin/perl
use strict;
use Data::Dumper;
my %hash;
$hash{'key1'}{'key2'} = 'value';
print "\nDump of \%hash (1):\n";
print Dumper \%hash;
# This print statement is actually altering the hash
print "\n\"$hash{'key0'}{'key1'}{'key2'}\"\n";
print "\nDump of \%hash (2):\n";
print Dumper \%hash;
The result is:
Dump of %dtoHash (1):
$VAR1 = {
'key1' => {
'key2' => 'value'
}
};
""
Dump of %dtoHash (2):
$VAR1 = {
'key1' => {
'key2' => 'value'
},
'key0' => {
'key1' => {}
}
};
The "print" statement is the only thing that can possibly be altering the hash. Indeed, comment it out and the 2nd dump is normal.
I have reproduced this on multiple versions of perl 5, up to and including 5.26.3 (on CentOS 8).
Why is the "print" statement altering the hash?
Any explanation (or even better, advice on how to avoid it) would be much appreciated.
Thanks in advance.
-
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.