sub by_ip { # Split the two ip addresses up into octets my ($a1, $a2, $a3, $a4) = split /\./, $a; my ($b1, $b2, $b3, $b4) = split /\./, $b; # Check to see if the first octets are the same if ($a1 == $b1) { # If the first octets are the same, check # the second octets if ($a2 == $b2) { # Ditto for the third octets if ($a3 == $b3) { # If the first 3 octets # of each address are # the same, return the # comparison of the last # octet $a4 =~ s/^([0-9]+)/$1/; $b4 =~ s/^([0-9]+)/$1/; return $a4 <=> $b4; } else { # 3rd octets were different # so return their comparison return $a3 <=> $b3; } } else { # 2nd octets were different so # return their comparison return $a2 <=> $b2; } } else { # Best case: The first octets were # different so we can return their # comparison immediately return $a1 <=> $b1; } } my @sorted = sort by_ip @unsorted; #### my @sorted = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, sprintf("%03.f%03.f%03.f%03.f", split(/\./, $_))] } @unsorted; #### @mapped = map { [$_, sprintf("%03.f%03.f%03.f%03.f", split(/\./, $_))] } @unsorted; @sorted = sort { $a->[1] cmp $b->[1] } @mapped; @sorted = map { $_->[0] } @sorted;