如何在 Perl 中创建哈希的哈希?
根据我目前对 Perl 中哈希值的理解,我希望这段代码能够打印“hello world”。它什么也不打印。
%a=();
%b=();
$b{str} = "hello";
$a{1}=%b;
$b=();
$b{str} = "world";
$a{2}=%b;
print "$a{1}{str} $a{2}{str}";
我假设哈希就像数组,那么为什么我不能让哈希包含另一个哈希呢?
Based on my current understanding of hashes in Perl, I would expect this code to print "hello world." It instead prints nothing.
%a=();
%b=();
$b{str} = "hello";
$a{1}=%b;
$b=();
$b{str} = "world";
$a{2}=%b;
print "$a{1}{str} $a{2}{str}";
I assume that a hash is just like an array, so why can't I make a hash contain another?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您应该始终使用“use strict;”在你的程序中。
使用引用和匿名哈希。
{%b}
创建对哈希%b
副本的引用。您需要在此处复制,因为稍后会清空它。You should always use "use strict;" in your program.
Use references and anonymous hashes.
{%b}
creates reference to copy of hash%b
. You need copy here because you empty it later.哈希值的哈希值第一次就很难正确。在这种情况下
,它将带您到达您想去的地方。
有关二维数据结构的详细信息,请参阅
perldoc perllol
珀尔。Hashes of hashes are tricky to get right the first time. In this case
will get you where you want to go.
See
perldoc perllol
for the gory details about two-dimensional data structures in Perl.简短回答:哈希键只能与标量相关联,而不能与哈希相关联。为了做你想做的事,你需要使用参考。
我建议您阅读 perlreftut,而不是重新散列(呵呵)如何创建多级数据结构。 perlref 更完整,但一开始有点让人不知所措。
Short answer: hash keys can only be associated with a scalar, not a hash. To do what you want, you need to use references.
Rather than re-hash (heh) how to create multi-level data structures, I suggest you read perlreftut. perlref is more complete, but it's a bit overwhelming at first.
迈克,亚历山大的答案是正确的。
还有一个提示。如果你刚刚学习哈希,perl 有一个名为 Data::Dumper 的模块,它可以为你漂亮地打印你的数据结构,当你想检查你的数据结构有什么值时,这真的很方便。
当你打印这个时它会显示
Mike, Alexandr's is the right answer.
Also a tip. If you are just learning hashes perl has a module called Data::Dumper that can pretty-print your data structures for you, which is really handy when you'd like to check what values your data structures have.
when you print this it shows
Perl 喜欢扁平化你的数据结构。这通常是一件好事......例如,
(@options, "another option", "yet another")
最终成为一个列表。如果您确实打算将一个结构放在另一个结构中,则内部结构需要作为参考。像这样:
大括号表示一个散列,您用 %b 中的值填充该散列,并作为引用而不是直接散列返回。
您也可以说
但这会使 %b 的更改也更改 $a{1} 。
Perl likes to flatten your data structures. That's often a good thing...for example,
(@options, "another option", "yet another")
ends up as one list.If you really mean to have one structure inside another, the inner structure needs to be a reference. Like so:
The braces denote a hash, which you're filling with values from %b, and getting back as a reference rather than a straight hash.
You could also say
but that makes changes to %b change $a{1} as well.
我需要创建 1000 条员工记录来测试 T&A 系统。员工记录存储在哈希中,其中键是员工的身份号码,值是其姓名、出生日期和雇用日期等的哈希。以下是如何...
I needed to create 1000 employees records for testing a T&A system. The employee records were stored in a hash where the key was the employee's identity number, and the value was a hash of their name, date of birth, and date of hire etc. Here's how...