Jul
13
Sorting IP Addresses
ByThe 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 Comment
You must be logged in to post a comment.