I was recently helping someone debug code in which the pass a hash to a subroutine by reference. They had done something like:
%foo = ( a => 1, b => 2, c => 3 };
sub mysub {
my %x = shift;
...
}
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:
my %foo = ( a => 1, b => 2, c => 3 );
mysub(\%foo);
sub mysub {
my %x = %{scalar shift};
foreach ( sort keys %x ) {
print "$_ -> $x{$_}\n";
}
}
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 = shift;
my %x = %{$x};
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};
foreach ( sort keys %x ) {
print "$_ -> $x{$_}\n";
}
}
The above code prints out nothing. What is magic about adding that "scalar"???
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.