Wednesday, April 13, 2011

How to Sort an Array by Length and Alphabetically in Perl

use strict;
use warnings;

# 1. Define the list of words
my @words = qw(This is a list of words using qw);

# 2. Sort the array using multiple criteria
my @sorted_words = sort {
    # Primary sort: Compare string lengths numerically
    length($a) <=> length($b) 
        || 
    # Secondary sort: If lengths are equal, compare alphabetically (case-insensitive)
    lc($a) cmp lc($b)
} @words;

# 3. Change the array separator to a newline and print
local $" = "\n";
print "@sorted_words\n";

No comments: