scs scs - 5 months ago 10
Perl Question

Sorting of uppercase and lowercase strings

I am trying to sort uppercase and lowercase strings in perl in alphabetical order. However, for some reason perl first sorts the uppercase strings and then the lowercase strings (see example below).

#!/usr/bin/perl
use strict;
use warnings;

my @array = ("abc","def","PQR","STW");
@array = sort @array;

foreach (@array){
print "$_ \n";
}


Output:

PQR
STW
abc
def

Answer

You need case insensitive sorting, accomplished by explicitly specifying the sorting criterion

my @sorted = sort { "\L$a" cmp "\L$b" } @array;

or, better

use feature qw(fc);
my @sorted = sort { fc($a) cmp fc($b) } @array;

The fc is specifically made for this. Also see sort, under Examples.