Sorting IP Addresses

The following will sort an array of IP addresses in @in and the sorted IP addresses will be in @out.

@out = sort {
    pack('C4' => $a =~ /(d+).(d+).(d+).(d+)/)
    cmp
    pack('C4' => $b =~ /(d+).(d+).(d+).(d+)/)
} @in;

What this does is it forms a string of four bytes out the IP address octet using the pack() function then sorts it lexicographically.

See also Sorting Section Numbers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.