Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating Random Strings

Status
Not open for further replies.

BryanY

MIS
Aug 18, 2001
54
US
Basically I would like to be able to specify a string length and generate a random string value.

EX: string length = 7 output: fwirvbt

I presume that I would use the rand() function, but I'm not sure how i would use it to generate character values.

Thanks!
 
maybe create an array of all 26 letters and then loop 7 times grabbing chars based on a random index of 0-25.


Trojan.


 
I'm not a Perl expert, so there is probably a more elegant way to do this, but the following is code from a script I wrote recently. This chooses four letters and two digits at random:

Code:
  for($count = 0; $count < 4; $count++) {
    $data[$count] = chr(int(rand(26))+65);
  }
  for($count = 4; $count < 6; $count++) {
    $data[$count] = int(rand(10));
  }

 
Code:
my @char_set = ('a'..'k', 'm'..'n', 'p'..'z');
my $random = '';
$random .= $char_set[rand(@char_set)] for (1..7);
print $random;


note that l (L) and o (O) are missing because they look too much like 1 (one) and 0 (zero), but just use:

my @char_set = ('a'..'z');

if you want to include them.
 
How about this
Code:
print "give me length: ";
$length = <STDIN>;
chomp $length;
@chars = (97..122);
print "Randon string with $length characters: ";
print chr $chars[int(rand(27))] for (1..$length);
print "\n";


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top