I have a hash that I sorted by values greatest to least. How would I go about getting the top 5? There was a post on here that talked about getting only one value.
What is the easiest way to get a key with the highest value from a hash in Perl?
I understand that so would lets say getting those values add them to an array and delete the element in the hash and then do the process again?
Seems like there should be an easier way to do this then that though.
My hash is called %words.
Edited Took out code as the question answered without really needing it.
Your question is how to get the five highest values from your hash. You have this code:
Where you have your sorted hash keys. Take the five top keys from there?
Also some comments on your code:
It is a good idea to include the error message
$!in your die statement to get valuable information for why the open failed.Like I said in the comment, you do not need to escape characters or use alternations in a character class bracket. Use either:
This next part is a bit odd.
You read in the stopwords from a file… and then you delete the stopwords from
$_? Are you even using$_at this point? Moreover, you are redeclaring the@stopwordsarray in the loop header, which will effectively mean your new array will be empty, and your loop will never run. This error is silent, it seems, so you might never notice.Here you make a copy of
%words_count, which seems to be redundant, since you never use it again. If you have a big hash, this can decrease performance.This can be done in one line:
my $key_count = keys %words. More readable, in my opinion.Can also be abbreviated with the
+=operator:$value_cont += $words{$key}It is very good that you use strict and warnings.