use Socket; my @blocks; while() { chomp; my ($ip,$bits) = m,^(\d+(?:\.\d+){3})/(\d+)$, or next; push @blocks, unpack("B*",inet_aton($ip)); substr($blocks[-1],-$bits) = "#" x $bits if $bits = 32 - $bits; } my $str = ";" . join(";", sort @blocks) . ";"; 1 while $str =~ s/;([01]+)(#*);\1[01#]*;/;${1}${2};/g; 1 while $str =~ s/;([01]+)0(#*);\1.\2;/;${1}#${2};/g; my @blocks = $str =~ /[10#]+/g; foreach my $block (@blocks) { my $bits = 32 - ($block =~ tr/#/0/); print inet_ntoa(pack("B*", $block)),"/$bits\n"; }