Jul
13

Sorting IP Addresses

By celso

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

Leave a Comment

You must be logged in to post a comment.