在perl中初始化哈希引用
以下Perl代码打印在perl中初始化哈希引用,perl,hash,reference,Perl,Hash,Reference,以下Perl代码打印值: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; } 初始
值: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;
}
初始化空哈希引用
#!/usr/bin/perl
use warnings;
use strict;
my $Hash = {};
Init($Hash);
printf("Value:%d\n",$Hash->{Key});
sub Init
{
my ($Hash) = @_;
$Hash->{Key}=10;
}
我知道一个答案已经被接受了,但我认为有必要解释一下为什么这个程序一开始就这么做 直到
Init
函数($hash->{Key}=10
)的第二行自动创建哈希并将引用存储在$hash
标量中,才会创建哈希。这个标量是函数的局部变量,与脚本主体中的$Hash
变量无关
这可以通过修改Init
函数处理其参数的方式来更改:
sub Init {
my $Hash = $_[0] = {};
$Hash->{'Key'} = 10;
}
如果你解释为什么他原来的计划不起作用,我会投赞成票的。谢谢你的反馈。这是一个非常新的概念,所以我以后会记住它。如果哈希引用没有初始化,会传递给子例程什么?@Jean它只是发送一个未定义的标量。没有提及任何事情。