http://qs1969.pair.com?node_id=11113064

larrymenard has asked for the wisdom of the Perl Monks concerning the following question:

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.