slloyd has asked for the wisdom of the Perl Monks concerning the following question:

How do I sort an array of text values, ignoring case?
use strict; my @items=qw(A B C a b c); @items=sort(@items); foreach my $item (@items){ print "$item\n"; }
Desired output:
A a B b C c

-------------------------------
by me
http://www.basgetti.com
http://www.kidlins.com

Replies are listed 'Best First'.
Re: sorting text arrays and ignoring case
by matze (Friar) on Mar 09, 2006 at 23:57 UTC
    You can convert the array elements to lowercase while comparing them. With
    @items=sort { lc($a) cmp lc($b) } (@items);
    your code prints:
    A a B b C c

    Update: sort lists this with uc as example.
      That's not guaranteed to return the mentioned result. How about:
      @items = sort { lc($a) cmp lc($b) || $a cmp $b } @items;
Re: sorting text arrays and ignoring case
by GrandFather (Saint) on Mar 10, 2006 at 00:07 UTC

    A few other ways of writing out the contents of the array:

    print "@items\n"; print join ('\n', @items), "\n"; print "$_\n" for @items;

    DWIM is Perl's answer to Gödel
      Or how about

      { local $" = "\n"; print "@items\n"; }

      to get one item per line?

      Cheers,

      JohnGG

        Nope, all in a line with spaces between items. But a trick worth knowing.

        Update: the node I replied to seems to have completely chenged its contents. My reply is no longer relevant.


        DWIM is Perl's answer to Gödel