for my $i (keys %history) { last if $history{ $i } == ($histcount - $n); } my $last_nth = $history{ $i };