scs scs - 1 year ago 90
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).

use strict;
use warnings;

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

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



Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download