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
|