foreach my $key (sort keys %test) { #to foreach my $key (sort { $test{$a}[-1] <=> $test{$b}[-1] } keys %test) {