简体   繁体   English

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

[英]How can I sort Perl hashes whose values are array references?

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. 但是我想通过array[0]元素对哈希进行排序。 Then loop through 'em. 然后循环通过'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. 它并不一定是“一行”,但我希望找到一个不涉及重构哈希的解决方案。

foreach my $key (sort {$DataBase{$a}->[0] cmp $DataBase{$b}->[0] } keys %DataBase)

For the record (you probably come from a C background), Perl does not have pointers, but references : 对于记录(您可能来自C背景),Perl没有指针,但引用

Perl [...] allows you to create anonymous data structures, and supports a fundamental data type called a "reference," loosely equivalent to a C pointer. Perl [...]允许您创建匿名数据结构,并支持称为“引用”的基本数据类型,松散地等效于C指针。 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. 正如C指针可以指向数据和过程一样,Perl的引用可以引用传统的数据类型(标量,数组和散列)以及其他实体,例如子例程,类型字符串和文件句柄。 Unlike C, they don't let you peek and poke at raw memory locations. 与C不同,它们不会让你偷看和戳戳原始内存位置。

Similar, but not the same. 类似,但不一样。

C. C。

I think you are asking the same basic question as How can I sort a hash-of-hashes by key in Perl? 我想你问的是同样的基本问题, 如何在Perl中按密钥对哈希哈希进行排序? . My answer, which is in the Perl FAQ, shows you how to sort a hash any way that you like. 我的答案在Perl FAQ中,向您展示了如何按照您喜欢的方式对哈希进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM