4

下面的 Perl 代码打印Value:0. 除了在哈希引用传递给子例程之前向哈希添加一个虚拟键之外,还有其他方法可以解决它吗?

#!/usr/bin/perl 
use warnings;
use strict;

my $Hash;

#$Hash->{Key1} = 1234;

Init($Hash);

printf("Value:%d\n",$Hash->{Key});

sub Init
{
    my ($Hash) = @_;
    $Hash->{Key}=10;
}
4

2 回答 2

4

初始化一个空的哈希引用。

#!/usr/bin/perl 
use warnings;
use strict;

my $Hash = {};

Init($Hash);

printf("Value:%d\n",$Hash->{Key});

sub Init
{
    my ($Hash) = @_;
    $Hash->{Key}=10;
}
于 2013-09-05T02:55:56.000 回答
3

我知道答案已经被接受,但我认为值得解释为什么程序首先会以这种方式行事。

Init直到函数 ( )的第二行才创建散列,该函数$Hash->{Key}=10自动创建散列并将引用存储在$Hash标量中。$Hash这个标量是函数的局部变量,与脚本主体中的变量无关。

这可以通过修改Init函数处理其参数的方式来改变:

sub Init {
    my $Hash = $_[0] = {};
    $Hash->{'Key'} = 10;
}
于 2013-09-05T14:06:45.843 回答