#!/usr/bin/perl -w =head1 by_number This demonstrates the use of a custom sorting routine "by_number" which is designed to sort strings with embedded numbers in the same way that a human might expect, ie taking account of the magnitude of the number rather than the lexicographical ordering of it. This is especially good for sorting IP addresses - ie Input Alpha by_number 10.0.0.2 10.0.0.1 10.0.0.1 10.0.0.1 10.0.0.10 10.0.0.2 10.10.1.1 10.0.0.2 10.0.0.10 10.1.10.1 10.0.1.10 10.0.1.10 10.2.1.2 10.0.2.2 10.0.2.2 10.0.2.2 10.1.10.1 10.1.10.1 10.0.1.10 10.10.1.1 10.2.1.2 10.0.0.10 10.2.1.2 10.10.1.1 Try the program for a longer example. =cut use strict; my @list = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [$_, rand] } qw { 1 2 3 4 10 11 12 20 21 22 100 1000 a00 a10 a29 abc1 abc1a abc11b abc111a2 abc1b12 10.0.0.1 10.0.0.2 10.0.0.10 10.0.1.10 10.0.2.2 10.1.10.1 10.2.1.2 10.10.1.1 }; my $result = [ [ "Input", @list ], [ "Alpha", sort @list ], [ "by_number", sort by_number @list ], ]; for my $i (0..$#{$result->[0]}) { for my $j (0..$#$result) { printf "%14s", $result->[$j][$i]; } print "\n"; } # Embedded numeric sorter sorts IP addresses & xyz123 sub by_number { my @a = split /(\d+)/, $a; my @b = split /(\d+)/, $b; while (@a && @b) { my ($aa, $bb) = (shift(@a), shift(@b)); my $res = ($aa =~ /^\d/ && $bb =~ /^\d/) ? $aa <=> $bb : $aa cmp $bb ; return $res if $res; } return @a <=> @b; } =head2 PS I originally wrote the above split()s as my @a = split /(?