#!/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]->(); }