my $first = undef; my $last = undef; my $length = 1; while (my ($cid) = $sth2->fetchrow()) { if (!defined($first)) { $first = $cid; next; } if ($cid == $first+1 or (defined($last) and $cid == $last+1)) { $last = $cid; $length++; next; } if (!defined($last)) { undef($first); undef($last); $length = 1; next; } if ($cid > $last+1) { print "$first\t$last\t$length\n"; undef($first); undef($last); $length = 1; next; } } print "\n\n";