in reply to String randomness

As a point of interest, I use the following code to generate a random password:
sub GetRandomPassword { my ($passwordlen) = @_; if(!$passwordlen) { $passwordlen = 12; } $OK_CHARS='-a-zA-Z0-9_.@'; $randWord = ""; rand(time); # get first random value out of the way while( length($randWord) < $passwordlen ) { $achar = chr(int(rand(122))); $randWord .= $achar; $randWord =~ s/[^$OK_CHARS]//go; } return $randWord; }

Replies are listed 'Best First'.
Re: Re: String randomness
by Arien (Pilgrim) on Aug 16, 2002 at 09:02 UTC

    Why would you select random characters with values ranging from 0 to 121 and later delete the ones that you didn't want to use in the first place, when you already know with which characters (the ones in the string $OK_CHARS) you want to build your random word?

    You could just stick the characters you want to use in an array and pick the required number of random elements from the array, like so:

    sub randomPassword { my $length = shift || 12; my @OK_CHARS = ('a'..'z', 'A'..'Z', '0'..'9', qw[_ - . @]); my $password; for (1 .. $length) { $password .= $OK_CHARS[ int rand scalar @OK_CHARS ]; } return $password; }

    — Arien

Re^2: String randomness
by Aristotle (Chancellor) on Aug 16, 2002 at 11:52 UTC
    Much too complicated. Why generate a random character and then use a regex to delete it? Even Arien's good suggestion can be written briefer.
    my @pass_char = ('a'..'z', 'A'..'Z', 0 .. 9, qw(_ . @)); sub generate_password { my $len = shift || 12; my $pass; $pass .= $pass_char[rand @pass_char] for 1 .. $len; return $pass; }
    I can't resist golfing this a bit.. but the following is not necessarily for use in production. :-)
    my @pass_char = ('a'..'z', 'A'..'Z', 0 .. 9, qw(_ . @)); sub generate_password { return join '', map $pass_char[rand @pass_char], 1 .. (shift || 12 +); }
    ____________
    Makeshifts last the longest.
Re: String randomness
by Abigail-II (Bishop) on Aug 16, 2002 at 08:19 UTC
    rand(time); # get first random value out of the way
    What is the point of this line?

    Abigail