my $max = 100000000; my @list = ( [ 39887, 399900 ], [ 23, 900 ], [ 8000, 10000 ], [ 50000, 1000500 ], ); ### @list = sort { $a->[0] <=> $b->[0] } @list; @res = (0); $last = shift @list; for (@list) { if ($_->[0] > $last->[1] + 1) { push @res, $last->[0] - 1, $last->[1] + 1; $last = $_; } else { $last->[1] = $_->[1] if $_->[1] > $last->[1]; } } push @res, $last->[0] - 1, $last->[1] + 1; $res->[-1] < $max ? push @res, $max : pop @res; for (0 .. $#res) { print $res[$_], $_ % 2 ? "\n" : '-'; }