#! perl -slw use strict; my %hash; ++$hash{ <> } until eof(); my @top5; push @top5, sort{ $hash{ $b } <=> $hash{ $a } } map scalar each %hash, 1 .. 5; while( my $next = each %hash ) { for my $i ( reverse 0 .. 4 ) { if( !defined( $top5[ $i ] ) or $hash{ $next } > $hash{ $top5[ $i ] } ) { splice @top5, $i, 0, $next; pop @top5 if @top5 > 5;; last; } } } chomp and print for @top5;