Perl: Table Sorting based on Hashes - by Eun Bae Kim (08/13/2018)
 

use strict;

my @aTable = (    {id => 'eb001', name => 'EBKim', score => 90},
                  {id => 'eb002', name => 'GDJin', score => 70},
                  {id => 'eb003', name => 'HCNoh', score => 80},
                  {id => 'eb004', name => 'IHYoo', score => 60},
                  {id => 'eb005', name => 'HCNoh', score => 90},
                  {id => 'eb006', name => 'GDJin', score => 60} );

# Sorting numerically (Ascending)
# @aNumbers = sort {$a <=> $b} @aNumbers;
# Sorting lexically in reversed order
# @aNumbers = sort {$b cmp $a} @aWords;



# Before being sorted
print "--------------------------------------------\n";
foreach my $pCur (@aTable) {
	printf("%-8s %-8s %03d\n", @{$pCur}{qw(id name score)});
}


# Sorted by Two Conditions
@aTable = sort{
    $b->{'name'} cmp $a->{'name'} ||
    $a->{'score'} <=> $b->{'score'}
} @aTable;

# After being sorted
print "--------------------------------------------\n";
foreach my $pCur (@aTable) {
	printf("%-8s %-8s %03d\n", @{$pCur}{qw(id name score)});
}



# For more information, refer to the following link
# http://www.perltutorial.org/perl-sort/