func(%hash);
is equivalent to
func('red', 'John', 'blue', 'Smith');
-or-
func('blue', 'Smith', 'red', 'John');
so
my $hash = $_[0];
is equivalent to
my $hash = 'red';
-or-
my $hash = 'blue';
Totally useless. Good thing you never use $hash
ever again.
Instead, you use the %hash
declared outside the sub. You can see this by reordering your code or by limiting the scope (visibility) of %hash
.
use strict;
use warnings;
{
my %hash = ('red' => "John", 'blue' => "Smith");
func(%hash);
}
sub func {
my $hash = $_[0];
print "$hash{'red'}\n";
print "$hash{'blue'}\n";
}
$ perl a.pl
Global symbol "%hash" requires explicit package name at a.pl line 11.
Global symbol "%hash" requires explicit package name at a.pl line 12.
Execution of a.pl aborted due to compilation errors.
The solution is to pass a reference.
use strict;
use warnings;
{
my %hash = ('red' => "John", 'blue' => "Smith");
func(\%hash);
}
sub func {
my $hash = $_[0];
print "$hash->{'red'}\n";
print "$hash->{'blue'}\n";
}