in reply to RE: RE: (Ovid) Re: General quesion
in thread General quesion

My question wasn't clear. I know that rand() returns a number between 0 and it's argument. But my point was, it returns a decimal; i.e. 3.14159, 25.70098, .00001, etc. Does perl automatically round the number down(or take the integer portion)? For eaxample, here is my code:

my $lRandomPassword = ''; my $lMaxLength = 10; my $length; my $lRand; my @lKeySpace = ('A'..'Z', 'a..z', 0..9); my $lKeySpaceSize = scalar(@lKeySpace); for ($length = 0; $length < $lMaxLength; $length++) { $lRand = int(rand($lKeySpaceSize)); $lRandomPassword .= $lKeySpace[$lRand]; }; $lRandomPassword;

Yes, I know the code is overly verbose, but the important question for me is, could I safely get rid of the int() call? Does perl take the integer portion of an array index?

Replies are listed 'Best First'.
RE: RE: RE: RE: (Ovid) Re: General quesion
by KM (Priest) on Aug 08, 2000 at 22:45 UTC
    Yes it does automatically takethe integer portion when using it for an array index. Using int() you will also simply get the integer portion, not a rounded number, so you using the int() is sort of a noop. To round, you could do this:

    my $foo = sprintf "%.0f", rand(100);
    But, to illustrate the answer to your question:

    perl -wle '@r = (1,2,3); print $r[$t = rand(3)]; print "$t"'; 2 1.28954588016495

    Cheers,
    KM

      Hmm. I'm not sure what you mean but I think you have made an incorrect assumption. Perl's int() just rounds down. It does not (necessarilly) convert the number into a long or unsigned long. You might want to read my previous node on Perl and floating point.

              - tye (but my friends call me "Tye")
        No wrong assumption here. I said int() get's the integer portion of the number, which echoes the FAQ:

        # perldoc -f int
        =item int EXPR
        
        =item int
        
        Returns the integer portion of EXPR. etc...
        
        Reread my post, I make no mention of int() rounding. And you are incorrect, Perl's int() doesn't round down, it simply gives you the integer portion.
        # perl -wle 'print int(1.66)'

        But, I do see where my wording may have been confuzzling, so I changed it a little.

        Cheers,
        KM