in reply to backwards if and while looping

For all of these "why not" people, why not just do:

$a = $b unless $error;

I know it doesn't work correctly if $a > $b. In my defense, some of the other solutions don't either. Anyway,

while ($a < $b) if not $error { $a++; }

looks pretty disgusting if you ask me. Whereas

$a++ while ! $error && $a < $b; if ( ! $error ) { $a++ while $a < $b; } do { $a++ while $a < $b } if ! $error;

all look a bit more elegant. Also

$a++ while not $error || $a >= $b; $a = $b unless $error or $a >= $b;

are cool, IMHO.

Replies are listed 'Best First'.
Re^2: backwards if and while looping
by Zed_Lopez (Chaplain) on Oct 01, 2004 at 23:18 UTC

    There's another case to account for... if $a or $b isn't integer, and their fractional parts differ (i.e. ($a - int $a) != ($b - int $b)) and $a < $b, then

    $a = $b unless $error or $a >= $b;

    (or similar examples in the thread) has a different result than the OP's code.

    I think it muddies the water to test $error every time through the loop, as some of these solutions do, when you only need to test it once. If $a or $b might be non-integer, here's one way to do it:

    if ($a < $b and !$error) { $a = int $b + ($a - int $a); $a++ if $a < $b; }

    I left out doing the floating point comparisons correctly...

    Updated: Fixed a dumb error in the code.

      Yeah, but who uses real numbers? ;-P