FireBird34 has asked for the wisdom of the Perl Monks concerning the following question:

After some time, I decided to (for the fun of it) make a password generator. Nothing to fancy. However, I seem to have some difficult in finding a snippit that will generate random characters. It is user defined, for the amount of random alpha/numeric characters, so I would need the generated alpha characters into an array for easy access. Not that hard, but I've never used the random function before =)

Replies are listed 'Best First'.
Re: Alpha/Numeric random generating
by traveler (Parson) on Nov 08, 2002 at 21:49 UTC
    You can also use String::Random. I use that for password generation. It is easy to use:
    use String::Random; my $rand = new String::Random; $rand->{'A'} = [ 'A'..'Z', 'a'..'z' ]; $rand->{'D'} = [ '1'..'9' ]; # no zero $passwd = $rand->randpattern("AAAADAAAD"); print "Password $passwd\n";
    Easy. It even lets you optionally choose the format of the password (which is the AAAADAAAD stuff) and the char set. I don't like zeroes in passwords: too hard to distinguish from O's when handing them out.

    HTH, --traveler

      Great, thanks for the help all! =)
Re: Alpha/Numeric random generating
by Zaxo (Archbishop) on Nov 08, 2002 at 21:39 UTC

    Restricting to alphanumerics, as your title suggests:

    #!/usr/bin/perl use warnings; use strict; use constant PWCHARS => ['0'..'9', 'A'..'Z', 'a'..'z']; sub rand_char { PWCHARS->[rand @PWCHARS] } my $foo; for (1..( ARGV[0] || 8 ) ) { $foo .= rand_char; } print $foo, $/;

    This runs from the command line, with the number of characters desired as the first argument. The default is eight characters.

    After Compline,
    Zaxo

      If you will be generating completely random passwords like this you may want to remove "lI10O" from the PWCHARS as they tend to look alike when printed on screen depending on the font. =)

      -Waswas
        Along these lines, adding some non-alphanumeric characters to the list will also make the passwords much more secure.

        And for the ultimate in security, throw in some extended Unicode ;-)
Re: Alpha/Numeric random generating
by waswas-fng (Curate) on Nov 08, 2002 at 21:38 UTC