my %hash = ( 4 => 20, 2 => 40, 3 => 30, 1 => 50, 5 => 10, ); while{ my $a = ((sort values %hash)); # key based on the second highest value my $b = ((sort { $hash{$b} <=> $hash{$a} } keys %hash)); print $b = $a; }