如何对值为数组引用的 Perl 哈希进行排序?

发布于 2024-07-18 04:44:27 字数 361 浏览 10 评论 0原文

嘿,我只是想知道是否有一个很酷的“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

又怨 2024-07-25 04:44:27
foreach my $key (sort {$DataBase{$a}->[0] cmp $DataBase{$b}->[0] } keys %DataBase)
foreach my $key (sort {$DataBase{$a}->[0] cmp $DataBase{$b}->[0] } keys %DataBase)
零度° 2024-07-25 04:44:27

根据记录(您可能来自 C 背景),Perl 没有指针,但是 参考文献

Perl [...] 允许您创建
匿名数据结构,以及
支持基本数据类型
松散地称为“参考”
相当于C指针。 正如C
指针可以指向数据,也可以指向数据
程序,Perl的参考资料可以
参考常规数据类型
(标量、数组和哈希)和
其他实体,例如子程序,
类型团和文件句柄。 与 C 不同,
他们不让你偷看
原始内存位置。

相似,但不一样。

C。

For the record (you probably come from a C background), Perl does not have pointers, but references:

Perl [...] allows you to create
anonymous data structures, and
supports a fundamental data type
called a "reference," loosely
equivalent to a C pointer. Just as C
pointers can point to data as well as
procedures, Perl's references can
refer to conventional data types
(scalars, arrays, and hashes) and
other entities such as subroutines,
typeglobs, and filehandles. Unlike C,
they don't let you peek and poke at
raw memory locations.

Similar, but not the same.

C.

顾冷 2024-07-25 04:44:27

我认为您在问与 如何在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文