@guy

A blog on technology and web culture

Guy Malachi


Source CodePerl Generate Random String

Here is a simple Perl function for generating random strings (using the characters 'A'-'Z','a'-'z', and '_').
To save it , paste it to a text file, and run it using Perl.
(or you can download it as a zip file)

#!/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: ".$random_string."\n";
print "Length: ".length($random_string)."\n";


© 2011 Guy Malachi atguy.com, All Rights Reserved