Archive for July, 2006

Jul
13

Sorting IP Addresses

Posted by: celso | Comments (0)

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

Categories : Notes, Perl
Comments (0)