如何在 Perl 哈希表中存储多个值?
直到最近,我一直将多个值存储到具有相同键的不同哈希中,如下所示:
%boss = (
"Allan" => "George",
"Bob" => "George",
"George" => "lisa" );
%status = (
"Allan" => "Contractor",
"Bob" => "Part-time",
"George" => "Full-time" );
然后我可以引用 $boss("Bob")
和 $status("Bob" )
但如果每个键可以拥有很多属性,并且我必须担心保持哈希值同步,这会变得很笨拙。
有没有更好的方法在哈希中存储多个值? 我可以将值存储为,
"Bob" => "George:Part-time"
然后用 split 分解字符串,但必须有一种更优雅的方法。
Up until recently, I've been storing multiple values into different hashes with the same keys as follows:
%boss = (
"Allan" => "George",
"Bob" => "George",
"George" => "lisa" );
%status = (
"Allan" => "Contractor",
"Bob" => "Part-time",
"George" => "Full-time" );
and then I can reference $boss("Bob")
and $status("Bob")
but this gets unwieldy if there's a lot of properties each key can have and I have to worry about keeping the hashes in sync.
Is there a better way for storing multiple values in a hash? I could store the values as
"Bob" => "George:Part-time"
and then disassemble the strings with split, but there must be a more elegant way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是标准方法,按照perldoc perldsc。
This is the standard way, as per perldoc perldsc.
哈希值的哈希值是您明确要求的。 Perl 文档中有一个教程风格的文档部分涵盖了这一点: Data Structure Cookbook 但是也许你应该考虑面向对象。 这是面向对象编程教程的典型示例。
像这样的事情怎么样:
Hashes of hashes is what you're explicitly asking for. There is a tutorial style piece of documentation part of the Perl documentation which covers this: Data Structure Cookbook But maybe you should consider going object-oriented. This is sort of the stereotypical example for object oriented programming tutorials.
How about something like this:
哈希可以包含其他哈希或数组。 如果您想按名称引用属性,请将它们存储为每个键的哈希值,否则将它们存储为每个键的数组。
有一个语法参考。
Hashes can contain other hashes or arrays. If you want to refer to your properties by name, store them as a hash per key, otherwise store them as an array per key.
There is a reference for the syntax.
%chums = ( "Allan" => {"Boss" => "George", "Status" => "Contractor"},
“鲍勃”=> {“老板”=> “彼得”,“状态”=> “兼职”} );
效果很好,但是有没有更快的方法来输入数据?
我正在考虑类似
%chums = (qw, x)( Allan Boss George Status Contractor Bob Boss Peter Status Part-time)
其中 x = 主键之后的辅助键数量,在本例中 x = 2,“Boss ”和“状态”
%chums = ( "Allan" => {"Boss" => "George", "Status" => "Contractor"},
"Bob" => {"Boss" => "Peter", "Status" => "Part-time"} );
works great but is there a faster way to enter the data?
I am thinking of something like
%chums = (qw, x)( Allan Boss George Status Contractor Bob Boss Peter Status Part-time)
where x = the number of secondary keys after the primary key, in this case x = 2, "Boss" and "Status"