It may make it a little clearer if you rename some of the variables. For the first version if you rename the global version of hash to ghash you get:

use strict; use warnings; my (%ghash)=('A'=>1, 'B'=>2, 'C'=> 3); rutine(\%ghash); sub rutine { my ($hash)=@_; print "$hash{A} $hash{B} $hash{C}\n"; }

which generates a syntax error in the print - %hash is not known.

In the second case you have already seen that the syntax check results in an error message that says "... Global symbol "%hash" requires explicit package name at ...", which is Perl's way of saying "I don't know a variable".

The thing that is confusing here is that Perl uses the sigil (the $, @, % or *) at the start of the variable to tell what type of thing is returned by the variable. So when you write:

print "$hash{A} $hash{B} $hash{C}\n";

Perl knows that the variable is a hash (from the {A}) and that you want a scalar as a result (from the $ sigil). However, if the variable is a reference you have to dereference it first. The print statement in rutine needs to be dereferenced:

print "$hash->{A} $hash->{B} $hash->{C}\n";

For a little further reading about references see the Tutorials sectin, in particular intro to references and References quick reference.


DWIM is Perl's answer to Gödel

In reply to Re: Reference curiosity? by GrandFather
in thread Reference curiosity? by tamaguchi

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.