Perl Sort Hash by Value

Problem

Given a log file similar to Linux syslog format as in the following example:

Write a Perl script to print the top 5 most repeated error messages.

Solution

Read the file line by line then split each line using “:” as separator then use the error message token as the key in a hash table and the error message count as the corresponding hash value. At the end you will get all error messages and their counts stored in the hash table. After that you need to sort the hash table by value not by key in decreasing order. The final step is to loop through the hash and print the first 5 values.

Code

Here is the code in Perl

Add a Comment

Your email address will not be published. Required fields are marked *