在 Perl 中,我们可以在哈希中为同一个键输入两个值而不丢失(覆盖)第一个值吗?
在我在 Perl 中声明哈希之后,
%hash1=(a=>"turkey",
b=>"india",
c=>"england",
d=>"usa")
如果我为已经存在的键分配一个新值,就像
$hash1{d}="australia";
我丢失了键“d”的先前值,即“usa”,因为当我这样做时,
print %hash1;
我看不到值“usa”...如何保留同一个键的两个值?
after i declare a hash in perl
%hash1=(a=>"turkey",
b=>"india",
c=>"england",
d=>"usa")
if i assign a new value to already existing key like
$hash1{d}="australia";
i am losing the previous value with key 'd' i.e "usa" because when i do
print %hash1;
i dont see the value "usa"...how to retain both the values for the same key?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
哈希键只能包含单个标量值,因此如果该值是字符串,则每个键只能包含一个项目。但是,没有什么可以阻止您将数组引用(也是标量)存储为值。为了使事情变得更容易,您可能应该只存储数组引用或字符串,而不是混合两者:
A hash key can only contain a single scalar value, so if that value is a string, you are stuck with one item per key. However, there is nothing stopping you from storing array references (which are also scalars) as the value. To make things easier, you should probably store only array references or strings, and not mix the two:
正如 JohnSmith 所说,使用数组的哈希:
并将其用作:
As JohnSmith said, use a hash of array:
and use it as:
您需要存储列表
示例的哈希值:
http://www.perlmonks.org/?node_id=1977
you need to store a hash of lists
example:
http://www.perlmonks.org/?node_id=1977
这个问题正好相当于问,如果我们首先为只能保存一个值的变量分配某个特定值,然后再为同一变量分配不同的值,我们是否可以访问我们刚刚覆盖的早期值。
同样的答案适用于两者:不,当然不是,如果不改变你的存储类、访问机制或两者,就不行。一就是一的意思。当您想出一种适用于简单无下标标量变量的机制时,您就可以解决整个类别的问题。
This question is precisely equivalent to asking whether if we first assign a variable that can hold only one value some particular value, but then later assign that same variable a different value, whether we can ever access the earlier value that we've just now overwritten.
The same answer applies to both: no, of course not, not without changing around your storage class, access mechanism, or both. One means one. When you have come up with a mechanism that works for a simple unsubscripted scalar variable, you will have done so for an entire class of problem.