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

How do you alphabetize an array?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: Alphabetize Array
by lilphil (Scribe) on Dec 08, 2001 at 08:33 UTC

    sort

    Syntax

    Category  list operator (list)
    Arguments  subname list
    Arguments  block list
    Arguments  list
    Return Value  list
    

    Definition

    This function sorts the list specified and returns the sorted list. The sort method can be specified with the optional subroutine or block argument. A subroutine may be specified that takes two arguments (passed as global package variables, $a $b) and returns TRUE if the first is less than or equal to the second by any criteria used. Similarly, a block can be specified (effectively an anonymous subroutine) to perform this function. The default sort order is based on the standard string comparison order.

    Example

    @a = ("z","w","r","i","b","a"); print("sort() ",sort(@a),"\n");

    Originally posted as a Categorized Answer.

Answer: How do you alphabetize an array?
by davido (Cardinal) on Oct 01, 2003 at 20:47 UTC

    my @unsorted = qw/Maggie Bart Lisa Homer Marge/; my @sorted = sort @unsorted;

    To sort case-insensitively, just change the second line to this:

    my @sorted = sort { lc($a) cmp lc($b) } @unsorted;

    See sort for a complete explanation.

Re: Alphabetize Array
by Anonymous Monk on Sep 17, 2002 at 22:10 UTC
    exaggerated bureau thoroughly

    Originally posted as a Categorized Answer.

Re: Alphabetize Array
by Anonymous Monk on Feb 27, 2002 at 18:13 UTC
    I never did like the example here, so here's my own:
    @array = (2,4,1);
    @array = sort(@array); 
      # Now the array equals (1,2,4);
    

    Originally posted as a Categorized Answer.

A reply falls below the community's threshold of quality. You may see it by logging in.