如何对值为数组引用的 Perl 哈希进行排序?
嘿,我只是想知道是否有一个很酷的“oneliner”可以对我的散列保存数组引用进行排序。 所以我的哈希中有一堆键/值,例如:
$DataBase{$key} = \@value;
但是我想按 array[0]
元素对哈希进行排序。 然后循环遍历它们。 我一开始是这样的:
foreach my $key (sort {$DataBase{$a} cmp $DataBase{$b} } keys %DataBase)
但这显然只是按数组的指针值对我的哈希进行排序。 它并不一定是“一行”,但我希望找到一种不涉及重建哈希的解决方案。
Hey I was just wondering if there is a cool "one liner" that would sort my hash holding array references. So I have a bunch of key/values in my hash something like:
$DataBase{$key} = \@value;
However I would like to sort the hash by the array[0]
element. Then loop through 'em. I had this to begin with:
foreach my $key (sort {$DataBase{$a} cmp $DataBase{$b} } keys %DataBase)
But that obviously just sorts my hash by the pointer value of the array. It doesn't exactly have to be "one line" but I was hoping for a solution that didn't involve reconstructing the hash.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据记录(您可能来自 C 背景),Perl 没有指针,但是 参考文献:
相似,但不一样。
C。
For the record (you probably come from a C background), Perl does not have pointers, but references:
Similar, but not the same.
C.
我认为您在问与 如何在 Perl 中按键对散列的散列进行排序?。 我的答案位于 Perl FAQ 中,向您展示如何以您喜欢的方式对散列进行排序。
I think you are asking the same basic question as How can I sort a hash-of-hashes by key in Perl?. My answer, which is in the Perl FAQ, shows you how to sort a hash any way that you like.