JCyow2020 has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks, I have a simple for loop which use the < less than operator in the TEST condition. This works as expected for an assigned scalar, but when I assign the scalar thru a rand call the loop goes 1 iteration beyond the < less than condition to <=. Your wisdom is greatly appreciated. J
#!/usr/bin/perl # use v5.10; use warnings; #use strict; $data_length = 5; printf "data length = %d\n",$data_length; for($k=0; $k < $data_length; $k++) # the includes up to $data_l +ength - 1 { printf "loop k = %d\n",$k; }# end for() $my_rand5 = rand(5); $data_length = 5 + $my_rand5; printf "data length = %d\n",$data_length; for($k=0; $k < $data_length; $k++) # the test includes $k == $d +ata_length { printf "loop k = %d\n",$k; }# end for()
Results are as follows: mytest data length = 5 loop k = 0 loop k = 1 loop k = 2 loop k = 3 loop k = 4 <- loop stops at N-1 data length = 9 loop k = 0 loop k = 1 loop k = 2 loop k = 3 loop k = 4 loop k = 5 loop k = 6 loop k = 7 loop k = 8 loop k = 9 <- loop goes 1 iteration too far
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: for loop less than test ill behaved...
by haj (Vicar) on Mar 30, 2020 at 15:37 UTC | |
|
Re: for loop less than test ill behaved...
by BillKSmith (Monsignor) on Mar 30, 2020 at 18:15 UTC | |
|
Re: for loop less than test ill behaved...
by jwkrahn (Abbot) on Mar 30, 2020 at 19:43 UTC | |
|
Re: for loop less than test ill behaved...
by Anonymous Monk on Mar 30, 2020 at 21:37 UTC |