Sort::Key::IPv4 - sort IP v4 addresses


  use Sort::Key::IPv4 qw(ipv4sort);

  my @data = qw(;
  my @sorted = ipv4sort @data;

  use Sort::Key::IPv4 qw(ipv4keysort);

  my @sorted = ipv4keysort { $_->ip_address } @hosts;


This module extends the Sort::Key family of modules to support sorting of IP v4 addresses and networks.

IPv4 addresses have to match the regular expression /^\d+\.\d+\.\d+\.\d+$/. For instance

IPv4 networks have to match the regular expression /^\d+\.\d+\.\d+\.\d+\/\d+$/. For instance


The functions that can be imported from this module are:

ipv4sort @data

returns the IPv4 addresses in @data sorted.

ripv4sort @data

returns the IPv4 addresses in @data sorted in descending order.

ipv4keysort { CALC_KEY($_) } @data

returns the elements on @array sorted by the IPv4 addresses resulting from applying them CALC_KEY.

ripv4keysort { CALC_KEY($_) } @data

is similar to ipv4keysort but sorts the elements in descending order.

ipv4sort_inplace @data
ripv4sort_inplace @data
ipv4keysort_inplace { CALC_KEY($_) } @data
ripv4keysort_inplace { CALC_KEY($_) } @data

these functions are similar respectively to ipv4sort, ripv4sort, ipv4sortkey and ripv4sortkey, but they sort the array @data in place.

netipv4sort @data
rnetipv4sort @data
netipv4keysort { CALC_KEY($_) } @data
rnetipv4keysort { CALC_KEY($_) } @data
netipv4sort_inplace @data
rnetipv4sort_inplace @data
netipv4keysort_inplace { CALC_KEY($_) } @data
rnetipv4keysort_inplace { CALC_KEY($_) } @data

These functions sort network addreses (composed by an IP and a network length pair with and slash separatin them).

pack_ipv4 $key

converts the IPv4 value to a 32 bits unsigned integer.

pack_netipv4 $key

converts an string of the format "" into two 32 bit unsigned numbers, the first representing the IP address and the second the network mask.


Sort::Key, Sort::Key::Maker


Report bugs by email or using the CPAN RT system at

This module is hosted at GitHub:


Copyright © 2007, 2009, 2012 by Salvador Fandiño, <>.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.8 or, at your option, any later version of Perl 5 you may have available.