Pass it a length and get a somewhat random string. Not recommended for sessioning, (use MD5, SHA1, etc for that). I just needed 4 digit somewhat random strings so pulling in MD5 seemed overkill.
sub random_string { my $length = shift || 2; my @chars = ('a'..'z','A'..'Z',0..9); join ('',map{ $chars[ rand() * @chars ] } (1..$length)); }

Replies are listed 'Best First'.
Re: Generate (somewhat) Random Strings
by Anonymous Monk on Jun 25, 2003 at 03:07 UTC
    This is basicaly the same but changed the rand() * @chars to something more intuitive when your reading it. I'm want to make one that lets you pass an array of possible letters to (no perl on this comp though :-( )
    sub RandomString { my $len = shift || 15; my @chars = ( "A".."Z", "a".."z", 0..9); return join '', map { $chars[ rand @chars ] } 1..$len; }
      I suppose rand() * N is a holdover from C. Here's a newer version that let's you pass as a second argument, a list or array reference of characters to use. The length will be combined elements length and not string length.
      sub random_string { my $length = shift || 2; my @chars = ('a'..'z','A'..'Z',0..9); @chars = UNIVERSAL::isa($_[0],'ARRAY') ? @{$_[0]} : @_ if @_; join ('',map{ $chars[ rand @chars ] } (1..$length)); } # Example print random_string(5,[qw(foo bar base )]),"\n"; print random_string(5,'a'..'f',0..9 ),"\n";


      -Lee

      "To be civilized is to deny one's nature."