Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: backwards if and while looping

by !1 (Hermit)
on Oct 01, 2004 at 22:16 UTC ( #395769=note: print w/replies, xml ) Need Help??

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

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://395769]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2021-09-24 16:18 GMT
Find Nodes?
    Voting Booth?

    No recent polls found