use Net::Netmask; my @blocks = (...); # list of your cidr blocks my @sorted = sort { ($a->bits <=> $b->bits) || ($a->base <=> $b->base) } @blocks; my @children; my @parent; for my $i (0..$#sorted) { for (my $j = $i-1; $j >= 0; $j--) { if ($sorted[$j]->contains($sorted[$i])) { $parent[$i] = $j; # or = $sorted[$j]; push(@{$children[$j]}, $i); # or $sorted[$i] last; } } } #### unshift(@sorted, new Net::Netmask("0.0.0.0/0")); # one subnet to rule them all