perlの複数項目ソート

初めてのPerl 第6版

初めてのPerl 第6版

perlの複数項目ソートのサンプル

#test data
my @data = (
    'A, 1, Type-1',
    'C, 6, Type-2',
    'B, 4, Type-3',
    'A, 3, Type-4',
    'A, 2, Type-5',
    'B, 9, Type-6',
    'C, 3, Type-7');

#sort
@data = map {$_->[0]}
            sort {$a->[1] cmp $b->[1] or $b->[2] <=> $a->[2]}
                 map {[$_, split /,/]} @data;
                 
#結果
foreach(@data){
    print($_."\n");
}

# 項目1と項目2によるソート結果
# A, 3, Type-4
# A, 2, Type-5
# A, 1, Type-1
# B, 9, Type-6
# B, 4, Type-3
# C, 6, Type-2
# C, 3, Type-7