my $order_by_size_rs = $all_subnets_rs->search({'source'=>$source},{'order_by'=>{'-asc','mask'}}); while( my $network = $order_by_size_rs->next ) { my $overlaping_nets_rs = $net_rs->search({ 'mask' => { '>', $network->mask() }, 'bitpattern' => { 'like', $network->bitpattern().'%' }, }, { 'order_by'=>{'-asc',['mask','start']} }); if( $overlaping_nets_rs->count ) { printf "Subnet %s/%d (%s) has %d overlaps:\n", $network->ip, $network->mask, $network->name, $overlaping_nets_rs->count; ... # Code to add the overlaps to the report. } }