Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Sort Hash of Arrays

I have a hash of arrays that looks like this:

{ $key, [$val1, $val2] }

I'm trying to numerically sort by the second value of the array and print out the entire hash. I've taken a look at the Schwartzian Transform posts, but I haven't seen one that does exactly what I want. I'm also very confused by the syntax and how to map the sorted values back into the original {$key, [$val1, $val2] } form. Any help would be appreciated!

like image 302
kurifu Avatar asked Nov 29 '22 15:11

kurifu


1 Answers

Not quite sure what you are referring to, but this is how you implement a sort routine on an array value, inside a hash:

my %hash = ( 'key1' => [ 1, 2 ], 'key2' => [ 2, 3 ] );

for my $key ( sort { $hash{$a}[1] <=> $hash{$b}[1] } keys %hash ) {
    print "$key => '", join(", ", @{$hash{$key}}), "'\n";
}
like image 52
TLP Avatar answered Dec 05 '22 23:12

TLP