my %hash = ('red' => "John", 'blue' => "Smith");
func (%hash);
sub func {
my $hash = $_[0];
print "$hash{'red'}\n";
print "$hash{'blue'}\n";
}
我将哈希发送到子例程,并将此哈希视为标量。如果是这样,我怎么可能通过调用它的键来转向哈希值?
答案 0 :(得分:12)
func(%hash);
相当于
func('red', 'John', 'blue', 'Smith');
-or-
func('blue', 'Smith', 'red', 'John');
所以
my $hash = $_[0];
相当于
my $hash = 'red';
-or-
my $hash = 'blue';
完全没用。好的,你永远不会再使用$hash
。
相反,您使用在子外部声明的%hash
。您可以通过重新排序代码或限制%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.
解决方案是传递参考。
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";
}
答案 1 :(得分:2)
因为%hash
的范围是整个程序。
答案 2 :(得分:0)
%hash应该是本地的。没有?
它是封闭范围的本地。范围由大括号分隔。但是你的宣言周围没有任何括号:
my %hash;
因此,%hash
在文件中的每个嵌套作用域内都可见。这是一个例子:
use strict;
use warnings;
use 5.016;
my $str = "hello";
if (1) { #new scope starts here
say "if: $str";
} #scope ends here
{ #new scope starts here
my $planet = "world";
say "block: $str";
for (1..2) { #new scope starts here
say "for: $str $planet";
} #scope ends here
} #scope ends here
#say $planet; #The $planet that was previously declared isn't visible here, so this looks
#like you are trying to print a global variable, which results in a
#compile error, because global variables are illegal with: use strict;
--output:--
if: hello
block: hello
for: hello world
for: hello world