Hai*_*rda 1 perl hash reference subroutine dereference
我想创建一个子程序,将元素(带有值的键)添加到先前定义的散列中.该子例程在循环中调用,因此哈希增长.我不希望返回的哈希覆盖现有元素.
最后,我想输出整个累积的哈希值.
现在它不打印任何东西.最终的哈希看起来是空的,但不应该.我已经尝试了哈希引用,但它并没有真正起作用.在简短的表单中,我的代码如下所示:
sub main{
my %hash;
%hash=("hello"=>1); # entry for testing
my $counter=0;
while($counter>5){
my(@var, $hash)=analyse($one, $two, \%hash);
print ref($hash);
# try to dereference the returning hash reference,
# but the error msg says: its not an reference ...
# in my file this is line 82
%hash=%{$hash};
$counter++;
}
# here trying to print the final hash
print "hash:", map { "$_ => $hash{$_}\n" } keys %hash;
}
sub analyse{
my $one=shift;
my $two=shift;
my %hash=%{shift @_};
my @array; # gets filled some where here and will be returned later
# adding elements to %hash here as in
$hash{"j"} = 2; #used for testing if it works
# test here whether the key already exists or
# otherwise add it to the hash
return (@array, \%hash);
}
Run Code Online (Sandbox Code Playgroud)
但这根本不起作用:子程序analyse
接收散列,但其返回的散列引用为空或我不知道.最后什么都没打印出来.
首先它说,它不是参考,现在它说:
Can't use an undefined value as a HASH reference at C:/Users/workspace/Perl_projekt/Extractor.pm line 82.
我的错误在哪里?
我很感谢任何建议.
数组在perl中变平,因此你的hashref会被插入@var
.
尝试这样的事情:
my ($array_ref, $hash_ref) = analyze(...)
sub analyze {
...
return (\@array, \@hash);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
125 次 |
最近记录: |