for my $time1 (sort keys %hash) { for my $time2 (sort keys %hash) { next if $time2 < $time1; ... # And do the math } }