in reply to Re: Re: Overlapping portions of sub strings
in thread Overlapping portions of sub strings
But in fact, your code is simpler, thus, better.use List::Util qw(max); $e = $range[$i][1] = max($e, $range[$j][1]);
But that of the infinite loop surprised me, a lot. I had assumed that the condition, the second expression in the for(;;) line, was being tested before any attempt at running the loop body, for each loop.
Result:print "before\n"; for(my $i = 5; $i < 2; $i++) { print " # $i\n"; } print "after\n";
before after
Result:print "before\n"; for(my $i = 5; $i < 10; $i++) { print " # $i\n"; if($i==7) { $i = 12; redo; } } print "after\n";
Ouch!before # 5 # 6 # 7 # 12 after
Hmm... perldoc -f redo apparently says:
The "redo" command restarts the loop block without evaluating the conditional again. The "continue" block, if any, is not executed.I recalled the latter, but forgot about the former. I guess it applies here as well. But what seems odd: the variable is initialized again, but the condition is not tested? Heh? While for the first loop, it is initialized and then tested? That is awkward.
I haste to say this... but a goto almost seems better:
Much as I despise goto, it seems like using redo as in your code, with the extra condition, is actually worse. Well, I can work around it:for (my $i = 0; $i < @range; $i++) { REDO: my $e = $range[$i][1]; for(my $j = $i+1; $j < @range; $j++) { unless($range[$j][0] > $e) { $range[$i][1] = $range[$j][1] if $range[$j][1] > $e; splice @range, $j, 1; goto REDO; } } }
which seems OK.@range = sort { $a->[0] <=> $b->[0] } @range; for (my $i = 0; $i < @range; $i++) { CURRENT: { my $e = $range[$i][1]; for(my $j = $i+1; $j < @range; $j++) { unless($range[$j][0] > $e) { $range[$i][1] = $range[$j][1] if ($range[$j][1] > $e); splice @range, $j, 1; redo CURRENT; } } } }
|
|---|