in reply to How do I create a list with the 10 most frequently used words in a file?

Jannejannesson:

Getting the "top N" or "bottom N" items of a list is often handled by sorting the keys by frequency of occurrence, and then keeping only the ones you want. You can do it like this:

# Build a list of keys sorted (descending because $b is on the left) b +y the number of occurrences my @sorted_by_count = sort { $count{$b} <=> $count{$a} } keys %count; # Print the top 10: print "$_ occurred $count{$_} times\n" for @sorted_by_count[0 .. 9];

Note: I didn't test the code, but it should be pretty close.

...roboticus

When your only tool is a hammer, all problems look like your thumb.

  • Comment on Re: How do I create a list with the 10 most frequently used words in a file?
  • Download Code

Replies are listed 'Best First'.
Re^2: How do I create a list with the 10 most frequently used words in a file?
by Jannejannesson (Novice) on Apr 29, 2019 at 15:27 UTC

    Thank you for the explanation as well as you're example. It worked great! Perlmonks is amazing!