[英]Initializing hash reference in perl
The following Perl code prints Value:0
. 以下Perl代码打印
Value:0
。 Is there a way to fix it other than by adding a dummy key to the hash before hash reference is passed to the subroutine ? 有没有办法解决它,除了在哈希引用传递给子例程之前向哈希添加一个虚拟键?
#!/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;
}
Initialize an empty hash reference. 初始化空哈希引用。
#!/usr/bin/perl
use warnings;
use strict;
my $Hash = {};
Init($Hash);
printf("Value:%d\n",$Hash->{Key});
sub Init
{
my ($Hash) = @_;
$Hash->{Key}=10;
}
I know that an answer has already been accepted, but I figured it was worth explaining why the program acted this way in the first place. 我知道答案已被接受,但我认为值得解释为什么该计划首先采取这种方式。
The hash is not created until the second line of the Init
function ( $Hash->{Key}=10
), which automatically creates a hash and stores a reference in the $Hash
scalar. 直到
Init
函数的第二行( $Hash->{Key}=10
)才会创建哈希,它会自动创建哈希并在$Hash
标量中存储引用。 This scalar is local to the function, and has nothing to do with the $Hash
variable in the body of the script. 该标量是函数的本地标量,与脚本正文中的
$Hash
变量无关。
This can be changed by modifying the way that the Init
function handles its arguments: 这可以通过修改
Init
函数处理其参数的方式来改变:
sub Init {
my $Hash = $_[0] = {};
$Hash->{'Key'} = 10;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.