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

    The rand function returns a fractional number, but you just print the integer part with the %d format. In the last iteration $k is still less than $data_length which you'll see easily if you print using the %fformat, or just use print instead of printf.

Re: for loop less than test ill behaved...
by BillKSmith (Monsignor) on Mar 30, 2020 at 18:15 UTC

    Refer rand.

    Apply int to the value returned by rand if you want random integers instead of random fractional numbers. For example, int(rand(10)) returns a random integer between 0 and 9 , inclusive.
    Bill
Re: for loop less than test ill behaved...
by jwkrahn (Abbot) on Mar 30, 2020 at 19:43 UTC

    Or you could use a different type of for loop:

    $ perl -le' my $my_rand5 = rand( 5 ); my $data_length = 5 + $my_rand5; printf "data length = %d\n", $data_length; for my $k ( 0 .. $data_length - 1 ) { printf "loop k = %d\n", $k; } ' 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
Re: for loop less than test ill behaved...
by Anonymous Monk on Mar 30, 2020 at 21:37 UTC
    A data-length of 5.1415926 is, after all, greater than 5 ...