in reply to Speed up my code

but its taking some time to finish this task.

It won't make any discernible difference on such a small dataset as your sample, but avoiding the sort for much larger datasets should be a win:

#! perl -slw use strict; my %hash; ++$hash{ <> } until eof(); my @top5; for( keys %hash ) { for my $i ( 0 .. 4 ) { if( !defined( $top5[ $i ] ) or $hash{ $_ } > $hash{ $top5[ $i +] } ) { splice @top5, $i, 0, $_; pop @top5 if @top5 > 5;; last; } } } print @top5; __END__ many hardships a million dollars love life apple pie you attempt things

Note: the difference between my output and your expected is due to there being no clear winner for 5th place.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

The start of some sanity?

Replies are listed 'Best First'.
Re^2: Speed up my code
by Tux (Canon) on Dec 14, 2011 at 14:50 UTC

    Much shorter :)

    $ perl -ne'$x{$_}++}END{print"$x{$_}\t$_"for(sort{$x{$b}<=>$x{$a}}keys +%x)[0..4]' test.txt 5 many hardships 2 a million dollars 2 love life 2 apple pie 1 you attempt things

    Enjoy, Have FUN! H.Merijn
Re^2: Speed up my code
by BrowserUk (Patriarch) on Dec 14, 2011 at 14:54 UTC

    Update: Ignore this. The optimisation broke it.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?