geekondemand has asked for the wisdom of the Perl Monks concerning the following question:
It was clear to me that the assignment a scalar reference directly to a hash variable would result in a hash containing a single pair, with key the actual reference value, and value undef. I usually shift onto a scalar variable and then use a dereference operator (->) in the sub when I pass hashes around. The person I was helping wanted to keep the hash variable %x, however. So I tried a couple things and eventually got this to work:%foo = ( a => 1, b => 2, c => 3 }; sub mysub { my %x = shift; ... }
That %x = %{scalar shift} is a pretty nifty little incantation. I tried to figure out why it works. Based on my experience, clearly this works:my %foo = ( a => 1, b => 2, c => 3 ); mysub(\%foo); sub mysub { my %x = %{scalar shift}; foreach ( sort keys %x ) { print "$_ -> $x{$_}\n"; } }
However, when I tried to simplify the code above, I was started that this does NOT work:my %foo = ( a => 1, b => 2, c => 3 ); mysub(\%foo); sub mysub { my $x = shift; my %x = %{$x}; foreach ( sort keys %x ) { print "$_ -> $x{$_}\n"; } }
The above code prints out nothing. What is magic about adding that "scalar"???my %foo = ( a => 1, b => 2, c => 3 ); mysub(\%foo); sub mysub { my %x = %{shift}; foreach ( sort keys %x ) { print "$_ -> $x{$_}\n"; } }
|
|---|