我想为一个由前一个哈希值构造的数组添加一个哈希值。 让我们说,我们有一个哈希:
( a=>1, b=>2, c=>3, d=>4)
我想将它转换为包含以下内容的哈希数组:
[
('key' => 'a', 'value' => 1),
('key' => 'b', 'value' => 2),
('key' => 'c', 'value' => 3),
('key' => 'd', 'value' => 4),
]
为此,我写下了以下片段:
%hash = (a=>1,b=>2, c=>3, d=>4);
@arr = ();
foreach(keys %hash) {
# Making a hash
%temp = ('key' => $_, 'value' => $hash{$_});
# Getting its reference
$hashref = \%temp;
# Push the reference of hash in the array
push( @arr, $hashref);
# Print it to know its value
print $_.' '.$hash{$_}."\n";
}
foreach(@arr) {
# Deref the hash
%h = %{$_};
# Print the element
print 'elem: '.$h{'key'}."\n";
# Print the reference
print "Ref: ";
print ref $_."\n";
# Print the keys in hash
print "keys in hash: ".keys %h;
print "\n";
}
但是输出只包含四个只有一个引用的条目:
c 3
a 1
b 2
d 4
elem: d
Ref: keys in hash: 2
elem: d
Ref: keys in hash: 2
elem: d
Ref: keys in hash: 2
elem: d
Ref: keys in hash: 2
为什么要添加重复项? 有关添加所有值的建议吗?
可以在此处尝试代码:http://ideone.com/OIZiGZ
我已经查看了许多答案,然后在它不起作用时到达这里。
答案 0 :(得分:1)
您每次都要添加对相同%temp
哈希的引用。
将您的代码更改为:
my %temp = ('key' => $_, 'value' => $hash{$_});
每次循环%temp
都是不同的哈希值。