Home » Programming » Perl » Group by, Count, and Sorting using Perl Script

Group by, Count, and Sorting using Perl Script

The Perl Programming Language

The Perl Programming Language

GROUP BY commonly used in Database SQL query to aggregate data to group the result-set by one or more columns. GROUP BY will be transforms a result set to produce one row for each unique value of grouping variables. Combine by COUNT will be output count rows of each group element. Group by usually combine with count when used in a report of a data. Below is sample of group by script by Perl script which combines by count and sorting the count values.

Perl Script to Group by, Count,and Sorting

groupby.pl

die " Usage: $0 \n" unless $ARGV[0];
%arrText=();

$fileName = $ARGV[0];
open(fileData,$fileName);
while(){
  $_ =~ s/(\r|\n)+//gi;
  $arrText{$_} = $arrText{$_} + 1;
}

foreach $key (sort {$arrText{$b} >= $arrText{$a}} keys %arrText){
	print $key." --> ".$arrText{$key}."\n";
}

exit;

Supply Script with Input Text

input_string.txt

mozilla
opera
chrome
firefox
ie
chrome
safari
k-meleon
firefox
chrome

Result of Script with Input Text

C:\Perl\script\text_processor>perl groupby.pl input_string.txt
chrome --> 3
firefox --> 2
mozilla --> 1
ie --> 1
k-meleon --> 1
opera --> 1
safari --> 1

Supply Script with Input Number

input_number.txt

500
20
50
100
500
50
20
10
20
90
10

Result of Script with Input Number

C:\Perl\script\text_processor>perl groupby.pl input_number.txt
20 --> 3
500 --> 2
10 --> 2
50 --> 2
90 --> 1
100 --> 1

Incoming search terms: