Random Password Generator - Using Perl

© copyright 01.Jan.2002 by Paul Bradley filed under Perl


[Ad] need a break from coding?

Hoseasons Villas

While working on a recent project, I needed some code to generate a random password for new users who registered with the system. The subroutine below demonstrates how you can generate random passwords of different lengths using Perl.

Random Password Generator - Perl Code

sub randomPassword {
my $password;
my $_rand;

my $password_length = $_[0];
    if (!$password_length) {
        $password_length = 10;
    }

my @chars = split(" ",
    "a b c d e f g h i j k l m n o
    p q r s t u v w x y z - _ % # |
    0 1 2 3 4 5 6 7 8 9");

srand;

for (my $i=0; $i <= $password_length ;$i++) {
    $_rand = int(rand 41);
    $password .= $chars[$_rand];
}
return $password;
}

Copy and paste the above subroutine into your Perl script. If you leave the password length parameter out when calling the routine, the code will create a password which is 10 characters long.

Password Example Usage:

create a password which is 6 characters long

 my $password = randomPassword(6);

print a password which is 12 characters long

 print "password = ", randomPassword(12);

 

 


If you have found this article helpful or useful please consider linking to it, emailing it to friends, or share it with others using social sites like del.icio.us, Stumble Upon or Twitter.

Paul Bradley

About the Author
Paul Bradley is a VB.NET software developer living and working in Cumbria. He provides PHP & MySQL bespoke development services via his software development company, Carlisle Software Limited.
He has over 20 years programming experience.

Other Popular Articles

Categories & Topics

Home · Apache · JavaScript · Perl · PDF · PHP · MySQL · MSSQL · TAR · Ubuntu Linux · Video · Visual Basic

Browse the complete article history, and if you like what you see; consider subscribing to the rss feed.