use strict; use warnings; my (@r1, %r1, @r2, $i, $j, $inp, $start, $end, $choice); @r1 = ( { 'name' => 'b', 'start' => 70, 'end' => 110 }, { 'name' => 'c', 'start' => 40, 'end' => 80 }, { 'name' => 'd', 'start' => 80, 'end' => 140 }, { 'name' => 'e', 'start' => 30, 'end' => 100 }, ); for (@r1) { $r1{$_->{'name'}}++; $_->{'stages'} = 1; } ### Generate combinations of overlapping ranges do { @r2 = (); for $i (0..$#r1) { for $j (0..$#r1) { ### Ranges are same, skip next if $i == $j; ### One range is completely inside other, skip next if $r1[$i]{'start'} <= $r1[$j]{'start'} && $r1[$i]{'end'} >= $r1[$j]{'end'} || $r1[$j]{'start'} <= $r1[$i]{'start'} && $r1[$j]{'end'} >= $r1[$i]{'end'}; ### i is not earlier range, skip next if $r1[$j]{'start'} < $r1[$i]{'start'}; ### Ranges do not overlap at all, skip next if $r1[$i]{'end'} < $r1[$j]{'start'}; ### Combined range already exists, skip next if $r1{"$r1[$i]{'name'}-$r1[$j]{'name'}"}++; ### Combine and add push @r2, { name => "$r1[$i]{'name'}-$r1[$j]{'name'}", start => $r1[$i]{'start'}, end => $r1[$j]{'end'}, stages => $r1[$i]{'stages'} + $r1[$j]{'stages'} }; } } push @r1, @r2; } while ($#r2 != -1); while (1) { print "\n"; exit if !getInputYes('Do you want to match a range?'); $start = int getInput('Enter a start value'); $end = int getInput('Enter an end value'); @r2 = (); for (@r1) { $_->{'diff'} = $start - $_->{'start'} + $_->{'end'} - $end; push @r2, $_ if $start >= $_->{'start'} && $end <= $_->{'end'}; } if ($#r2 == -1) { print "No matches found.\n"; next; } for (sort { $a->{'diff'} <=> $b->{'diff'} || $a->{'stages'} <=> $b->{'stages'} } @r2) { print "$_->{'name'} [$_->{'start'}-$_->{'end'}] is best match, with $_->{'diff'} difference and $_->{'stages'} stages.\n"; last; } } sub getInput { my $inp; while (1) { print "$_[0] : "; chomp($inp = ); return $inp if $inp; } } sub getInputYes { my $inp; while (1) { $inp = uc substr(getInput("$_[0] (Y/N)"), 0, 1); return 1 if $inp eq 'Y'; return 0 if $inp eq 'N'; }; }