[英]how to copy(insert) hash reference to another hash reference in perl?
最近開始做perl。 我正在閱讀舊代碼並試圖重寫一些東西。 我在這里有一個關於哈希引用的問題。
#declar anon hash ref that will be returned
my $store_hash = {};
foreach my $item (@list)
{
#this will iterate based on list
my $ret_hash = ops_getval($item, $user)
#do some magic here to map $ret_hash into $store_hash
}
ops_getval是一個返回ref hash類型的函數。 我想將這些值插入$ store_hash。 我該怎么做呢? 我可以直接做嗎
$store_hash = ops_getval($var1,$var2)
非常感激!
我認為這樣做的標准方法是:
@$store_hash{ keys %$ret_hash } = values %$ret_hash;
這ops_getval
對ops_getval
的所有調用返回的所有哈希值合並到$store_hash
。
另一種可能更清晰的方法,可能是以大量冗余數據復制為代價:
%$store_hash = (%$store_hash, %$ret_hash);
你會做的事情如下:
$store_hash->{$item} = $ret_hash
一般來說:
$hashref->{$key} = $value
請參閱此處了解更多信息: http : //perldoc.perl.org/perlref.html#Using-References
要清楚,您可以使用循環並完成此操作。
foreach ( keys%{ $ret_hash } ){
$store_hash->{ $_ } = $ret_hash->{ $_ } ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.