简体   繁体   中英

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. 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.

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 :

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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