Search code examples
perlsortinghashreferenceperl-data-structures

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.


Solution

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