我正在尝试调用一个过程,该过程通过引用填充哈希。对散列的引用作为参数给出。该过程填充哈希值,但是当我返回时,哈希值为空。请参阅下面的代码。 有什么问题?
$hash_ref;
genHash ($hash_ref);
#hash is empty
sub genHash {
my ($hash_ref)=(@_);
#cut details; filling hash in a loop like this:
$hash_ref->{$lid} = $sid;
#hash is generetad , filled and i can dump it
}
答案 0 :(得分:2)
您可能希望首先初始化hashref,
my $hash_ref = {};
因为autvivification在函数内部发生在另一个词法变量上。
(不太好)替代方法是在@_
数组中使用直接别名为原始变量的标量,
$_[0]{$lid} = $sid;
顺便说一句,请考虑use strict; use warnings;
所有脚本。
答案 1 :(得分:2)
来电者的$hash_ref
未定义。因此,sub中的$hash_ref
也未定义。 $hash_ref->{$lid} = $sid;
对子$hash_ref
进行自动生成,但没有任何内容将哈希引用分配给调用者的$hash_ref
。
解决方案1 :实际上传入哈希引用以分配给调用方的$hash_ref
。
sub genHash {
my ($hash_ref) = @_;
...
}
my $hash_ref = {};
genHash($hash_ref);
解决方案2 :利用Perl通过引用传递的事实。
sub genHash {
my $hash_ref = $_[0] ||= {};
...
}
my $hash_ref;
genHash($hash_ref);
-or-
genHash(my $hash_ref);
解决方案3 :如果哈希最初是空的,为什么不在子网站中创建呢?
sub genHash {
my %hash;
...
return \%hash;
}
my $hash_ref = genHash();