in reply to Quicky password sub

This might be faster because it doesn't have all of the checks for the range of acceptable chars. It precalculates the acceptable chars and stores them in an array in a closure so it only has to calculate and store once. You can adjust the chars that you want acceptable by changing the the assignment in the closure.

{ my @password_chars = ( 0..9,A..Z,a..z ); # acceptable chars sub Pass { my $password = ''; for ( 1..8 ) { $password .= $password_chars[rand(@password_chars)]; } return $password; } }

T.R. Fullhart, kayos@kayos.org

Replies are listed 'Best First'.
RE: RE: Quicky password sub
by chromatic (Archbishop) on May 02, 2000 at 19:07 UTC
    It's 50% faster on my machine to do this:
    { my @password_chars = ( 0 .. 9, 'A' .. 'Z', 'a' .. 'z' ); my $num_char = @password_chars; sub Pass { my $password = ''; $password .= $password_chars[rand($num_char)] for (1 .. 8); return $password; } }

      You can also just say rand(@password_chars) and get rid of the $num_char variable entirely.

      Also, as long as your are hard coding the iteraction as 'for (1..8)' you can gain even more speed by just doing it like this: (forgive my shortening of password_chars)

      sub Pass { return $p_c[rand(@p_c)] . $p_c[rand(@p_c)] . $p_c[rand(@p_c)] . $p_c[rand(@p_c)] . $p_c[rand(@p_c)] . $p_c[rand(@p_c)] . $p_c[rand(@p_c)] . $p_c[rand(@p_c)]; }
      You could even take out the "return"!
      very very cool chromatic. It took me a minute to see the change that
      you made, but wow! cool.