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

a 夏天 提交于 2019-12-12 14:24:24

问题


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.


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/827105/how-can-i-sort-perl-hashes-whose-values-are-array-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!