Thursday, January 8, 2009

[perl] - Generate a random password

The following code will generate a random password composed of uppercase/lowercase/special characters and digits.

sub generate_password {
  my $length = shift || 10;
  my @chars = ( "A" .. "Z", "a" .. "z", 0 .. 9, qw(! @ $ % ^ & * ) );
  my $password = join("", @chars[ map { rand @chars } ( 1 .. $length ) ]);
  return $password;
}

You can pass a number as parameter to the generate_password function that will determine the length of the new password.
Default length here is 10

No comments: