© copyright 01.Jan.2002 by Paul Bradley filed under Perl
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.
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.
create a password which is 6 characters long
my $password = randomPassword(6);
print a password which is 12 characters long
print "password = ", randomPassword(12);
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.