The Alphanum Algorithm: Perl Implementation
# The Alphanum Algorithm is an improved sorting algorithm for strings
# containing numbers. Instead of sorting numbers in ASCII order like
# a standard sort, this algorithm sorts numbers in numeric order.
#
# The Alphanum Algorithm is discussed at http://www.DaveKoelle.com
sub alphanum {
# $a and $b are automagically passed to alphanum.
# A copy of them has to be made, or else we will edit the global $a and $b
$a_copy=$a;
$b_copy=$b;
$n=0;
while ($n==0) {
# Get next "chunk"
# (A chunk is either a group of letters or a group of numbers)
($a_chunk) = $a_copy =~ /([\D]+|[\d]+)/;
$a_copy = substr($a_copy,length($a_chunk),length($a_copy)-length($a_chunk));
($b_chunk) = $b_copy =~ /([\D]+|[\d]+)/;
$b_copy = substr($b_copy,length($b_chunk),length($b_copy)-length($b_chunk));
# Compare the chunks
# Case 1: They both contain letters
if (($a_chunk =~ /\D+/) && ($b_chunk =~ /\D+/)) {
$n = $a_chunk cmp $b_chunk;
} else {
# Case 2: They both contain numbers
if (($a_chunk =~ /\d+/) && ($b_chunk =~ /\d+/)) {
$n = $a_chunk <=> $b_chunk;
} else {
# Case 3: One has letters, one has numbers; or one is empty
$n = $a_chunk cmp $b_chunk;
# If these are equal, make one (which one is arbitrary) come before
# the other (or else we'll be stuck in this "while $n==0" loop)
if ($n==0) { $n=1 }
} }
}
return $n;
}
To use this in Perl, you need to say @sorted_list = sort alphanum @unsorted_list;