Dear Monks,
I am a little confused about the way Perl treats hash references being passed into functions. Here is a test case:
#!/usr/local/bin/perl -w use strict "vars"; use strict "subs"; sub inter(\%) { printf "$_[0]\n"; printf "@_\n"; printf "$_[0]->{a}\n"; printf "$_[0]{a}\n"; } printf "ONE\n"; my %c = (a=>"a",b=>"b"); inter(%c); printf "TWO\n"; my $ref = "inter"; $ref->(%c); printf "THREE\n"; $ref->(\%c);
output:
ONE HASH(0x622430) HASH(0x622430) a a TWO a a a b b Use of uninitialized value in concatenation (.) or string at /home/smk +/prog/pl/interesting.pl line 10. Use of uninitialized value in concatenation (.) or string at /home/smk +/prog/pl/interesting.pl line 11. THREE HASH(0x622430) HASH(0x622430) a a
Questions:
1. The function definition specifies that the argument is a reference to a hash. Then why does block ONE in the code above need a hash to be passed to inter? If I change the line
inter(%c)
to
inter(\%c)
then I get a compilation error as follows:
Type of arg 1 to main::inter must be hash (not reference constructor) +at /home/smk/prog/pl/interesting.pl line 18, near "%c)" Execution of /home/smk/prog/pl/interesting.pl aborted due to compilati +on errors.
Why is this?

2. Why does the argument have to be a reference again if the function itself is being called by reference? (block THREE)

3. In block TWO, it looks like the function is treating the argument as an array.

4. Finally, inside the function, in the final two printfs, I am using different notations, one if $_[0] was a hash, and another if it was a reference. Both work similarly. How can this be explained?

Thanks a lot!


In reply to references and functions by jignasu

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.