我应该如何在多级 Perl 哈希中存储值?
我想做这样的事情。我记得在这样编程时,我遇到了一些价值观消失的问题。这种类型的结构对于哈希来说“正确/有效”吗?
my %VAR;
$VAR{SCALAR} = "test scalar";
$VAR{ARRAY}[0] = "test array";
$VAR{HASH}{NAME}[0] = "test hash array 1";
$VAR{HASH}{NAME}[1] = "test hash array 2";
$VAR{HASH}{NAME}[2]{SOMEHASH} = "test hash array hash 1";
$VAR{HASH}{NAME}[2]{ANOTHERHASH} = "test hash array hash 2";
I am looking to do something like this. I remember I had some issues with values disappearing when programming like this. Is this type of structure "correct/valid" for a hash?
my %VAR;
$VAR{SCALAR} = "test scalar";
$VAR{ARRAY}[0] = "test array";
$VAR{HASH}{NAME}[0] = "test hash array 1";
$VAR{HASH}{NAME}[1] = "test hash array 2";
$VAR{HASH}{NAME}[2]{SOMEHASH} = "test hash array hash 1";
$VAR{HASH}{NAME}[2]{ANOTHERHASH} = "test hash array hash 2";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这没有任何理由行不通。您看到什么问题?
如果你想确保你的数据结构看起来像你所期望的那样,我推荐类似
Data::Dumper
的东西:应该得到类似的东西:
I see no reason why this wouldn't work. What issues are you seeing?
If you want to make sure your data structure looks like what you'd expect, I recommend something like
Data::Dumper
:Should get something like:
这不完全是你的问题,但是......如果你实际上以这种方式构建数据结构,你可能会考虑更干净的“文字”语法:
主要的两个原因是可读性和 autovivification 错误。这并不是 不正确的 perl,但它可能会导致难以调试的问题,例如意外键入:
而不是
Which can't be an issues if you're using
This isn't exactly your question, but... if you're actually building the data structure in that fashion, you might consider a cleaner "literal" syntax:
The main two reasons are readability and autovivification bugs. That's not incorrect perl, but it can lead to hard-to-debug issues, such as accidentally typing:
instead of
Which can't be an issue if you're using
通常,当人们抱怨价值观消失时,是因为他们取代了价值观。当您分配给散列的任何部分时,即使它是引用值,您也会替换之前存在的值:
输出显示第二级的散列引用不再存在:
您只需小心以及分配内容的位置,就像分配任何其他变量一样。
Often when people complain about disappearing values it's because they replaced them. When you assign to any part of a hash, you replace the value that was there previously even if it was a reference value:
The output shows that the hash reference that was the second level is no longer there:
You just have to be careful what and where you assign things, just like you do with any other variable.