With a little side of applesauce...

Sunday, January 28, 2007

Perl - random string generator

I am always frustrated by the lack of simple random string generation in Python and BASH, so found this PERL quicky and modified it to only spit out the random string:


#!/usr/bin/perl

###########################################################
# Written by Guy Malachi http://guymal.com
# 18 August, 2002
###########################################################

# This function generates random strings of a given length
sub generate_random_string
{
my $length_of_randomstring=shift;# the length of
# the random string to generate

my @chars=('a'..'z','A'..'Z','0'..'9','_');
my $random_string;
foreach (1..$length_of_randomstring)
{
# rand @chars will generate a random
# number between 0 and scalar @chars
$random_string.=$chars[rand @chars];
}

return $random_string;
}

#Generate the random string
my $random_string=&generate_random_string(11);

print "$random_string";

I then call the Perl script from Python… and then grab the string from STDOUT. You have to love PERL :)

Original version of script is at:

http://guymal.com/mycode/generate_random_string/

1 comment:

Abhijith said...

thanks a lot!