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

Consider the code:
$h->{bar}=1; print "$h $$h{bar}\n";
It, as expected, outputs:
HASH(0x7fefc8) 1
Then consider the code:
$h->{bar}=1; $h='foo'; print "$h $$h{bar}\n";
Although the code is somewhat nonsensical, it outputs the expected:
foo
What I want to know is where I can look in the perl docs to predict this behavior:
$h='foo'; $h->{bar}=1; print "$h $$h{bar}\n";
Which outputs what more devout perl monks than I undoubedly expect:
foo 1

Replies are listed 'Best First'.
Re: Implicit Reference Assignment Surprisingly Doesn't Overwrite Prior Scalar
by Tanktalus (Canon) on May 05, 2014 at 04:20 UTC

    You're in need of some strictness.

    What's going on in your last example is what's called a symbolic reference. $h is 'foo'. And so $h->{bar} resolves $h to 'foo', and looks up a hash named 'foo'. If you printed out "$foo{bar}", you'd get the same 1 as you're getting with "$$h{bar}".

    And that confusion is why strict doesn't allow symbolic references. They were required at one time, but that was over twenty years ago, I think, so avoiding them is generally the right idea now, when there are other, better, ways to refer to other objects.

      Thanks! I actually did program in Perl4 back then but did not recall that twist. (And, yes, I did add 'use strict' after this happened.)
Re: Implicit Reference Assignment Surprisingly Doesn't Overwrite Prior Scalar
by choroba (Archbishop) on May 05, 2014 at 07:43 UTC