Perl: Natural sort part deux
If you want to sort an array naturally (the way a human would) you can use Perl's sort()
function, but use a custom sort method:
my @input = qw(foo foo250 foo12 foo23 bar999 bar7 bar17 bar99 18);
my @sorted = sort { natural(); } @input;
print join(", ", @sorted);
sub natural {
# Separate the word and numeric parts
my ($word_a, $num_a) = $a =~ /(.*?)(\d+|$)/;
my ($word_b, $num_b) = $b =~ /(.*?)(\d+|$)/;
#print "$a / $b: $word_a, $num_a, $word_b, $num_b\n";
# If the words are diff it's an alpha sort on the words
if ($word_a ne $word_b) {
return $word_a cmp $word_b;
# Words are the same, numeric sort the number part
} else {
return ($num_a || 0) <=> ($num_b || 0);
}
}
See also: Natural Sort