in reply to General quesion

Let's clean up your code a little bit, too:
#!/usr/bin/perl -w use strict; my @myarray=('a'..'z','A'..'Z','1'..'9'); my $mysamplepass; for (1..8) { $mysamplepass .= $myarray[rand(@myarray)]; } print $mysamplepass;
Notes: Hope this helps! Let me know if you have any questions.

Cheers,
Ovid

Update: Aargh!!! jlistf touched on most of these points while I was composing this. I need to type faster :(

Replies are listed 'Best First'.
RE: (Ovid) Re: General quesion
by johannz (Hermit) on Aug 08, 2000 at 00:52 UTC

    My turn to go Aargh!!! I just wrote pretty much this same code and I missed the for (1..8) optimization.

    Of course, I have an excuse since my code actually accepts the size for the password and if they go with a real large password, I would have to wait for the list to be created. Yeah, that's my excuse and I'm sticking to it. :-) Yes, I know it's a weak excuse, but it was the best I could come up with.

    One question though. When using a random number it returns a decimal. Does using it as an array index automagically int() it? 'Cause in my code, I explicitly call int around my rand call.

      When using a random number it returns a decimal. Does using it as an array index automagically int() it?

      Take a look at the scalar we're creating:

      $myarray[rand(@myarray)];
      You'll notice that rand is being passed @myarray. Since rand is expecting a scalar, @myarray is interpreted in a scalar context. Therefore, it returns the length of the array (52 in this case), which will cause rand to generate a random number from 0 to 51, which fits the array index quite nicely. Perhaps this would have been more clear:
      $myarray[rand($#myarray)];
      Cheers,
      Ovid
        But rand($#myarray) returns 0..50 not 0..51. $#array in a scalar context is always one less than @array in a scalar context.

        So, the idiom is:

        $random_item = $array[rand @array];

        Just cut-n-paste that!

        -- Randal L. Schwartz, Perl hacker

        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?