The BTree answer was horrible overkill.
It is a great idea if you needed to process the timepoints
as they come in. But a naive sorting solution is much
simpler and gets better control. After all we have to sort
the beginning and end of the intervals Just toss in the
timepoints as well. For instance if you want
to get closed intervals, you can do it like this:
#!/usr/bin/perl -w
use strict;
# The original data structure
my %interval = qw(
5 50
20 30
70 90
120 130
);
# The times
my @times = qw(4 9 30 98 125 500);
# Current nesting depth
my $depth = 0;
# Let us rearrange the interval information
# into events consisting of a time/action
my @events = map {[$_, 0, sub {++$depth}]} keys %interval;
push @events, map {[$_, 2, sub {--$depth}]} values %interval;
push @events, map {
my $time = $_;
[$_, 1, sub {print "Time $time is at depth $depth\n"}]
} @times;
# Sort it and read out the answer:
foreach my $event (
sort {
$a->[0] <=> $b->[0] or $a->[1] <=> $b->[1]
} @events
) {
$event->[2]->();
}
(And, of course, you can make the whole thing much cleaner,
this is just proof of concept code.)