marto9 has asked for the wisdom of the Perl Monks concerning the following question:

Hi peope, I've got a problem with this code. The loop never stops!
$rnumber = int(rand("100")); if (-e $file.".bak".$rnumber) { $origi = $file.".bak".$rnumber; while ($origi == $file.".bak".$rrnumber) { $rrnumber = int(rand("100")); } $newfile = $file.".bak".$rrnumber; move($file,$newfile); } else { $newfile = $file.".bak".$rnumber; move($file,$newfile); }

Replies are listed 'Best First'.
Re: Random number in while loop
by ikegami (Patriarch) on Jul 16, 2008 at 20:01 UTC

    == compares numbers, but you are feeding it strings. Use eq.

    perlop

      More specifically as to why it never stops, Perl treats not-numbers (such as your filenames) in a numeric context as having the numeric value 0. You're basically comparing two 0s then which are always equal. Had you used warnings you would have gotten a gripe Argument "bar" isn't numeric in numeric eq (==) at file.plx line 17. Had your filenames started with $rnumber as a prefix rather than having it as a suffix you would have gotten behavior more like you expect (since Perl would treat something like "44.spoo.bak" numerically as 44).

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.

Re: Random number in while loop
by toolic (Bishop) on Jul 16, 2008 at 20:12 UTC
    Your problem is that you are not using the strictures:
    use strict; use warnings;

    This would have given you this type of warning message:

    Argument isn't numeric in numeric eq (==)

    which (might) have led you to using the string operator eq instead of ==.

Re: Random number in while loop
by CountZero (Bishop) on Jul 16, 2008 at 21:31 UTC
    There is no need to double quote the number in the rand function. int(rand(100)) works just as well and saves you two keystrokes.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Random number in while loop
by marto9 (Beadle) on Jul 16, 2008 at 20:51 UTC
    Thx everyone for your help. I'll remember to use. ;) use strict; use warnings;