Speaking of elegant ways to get something complicated done with a minimum amount of good-old perling, here's an interesting algorithm:
sub random_string
{
my $max = shift;
return join '', map { ('a'...'z', '0'...'9', 'A'..'Z', '0'...'9')[rand 72] } (1..$max);
}
In case you couldn't figure it out yourself, it takes a single integer as input and generates a string of that many characters made up of random upper- and lowercase letters and digits.
Why do you use the ... operator instead of ..? And why have 2 sets of digits?
Strange, I posted a comment last week. Hasn't it arrived?
Sorry, but for some reason my junk filter went haywire and was banning all comments for the last couple of weeks.
I put in the range of digits twice because I figured that the random choice would otherwise be too skewed towards preferring characters over digits.
Yes, I should have used two dots instead of three. Sorry. Funny thing is: it still works!
The algorithm still slightly favours letters over digits (26 letters to 20 digits). The following routine may not be as short (although it contains enough Perlisms :-), but is not biased:
sub generate_password {
my $length = shift || 8;
my $password = "";
my @valid_chars = ( ['a' .. 'z', 'A' .. 'Z'], ['0' .. '9'] );
my @lengths = map { scalar @{$valid_chars[$_]}-1 } 0 .. $#valid_chars;
for (1 .. $length) {
my $type = rand 2;
$password .= $valid_chars[ $type ]->[ rand $lengths[$type] ];
}
return $password;
}
The three dots still work because in list context, they behave exactly as the double dot operator. Only in boolean context they behave differrently. It's documented in the "Range Operators" section of the perlop documentation.
By the way, posting code should be easier :-)
I guess I am always a stickler for terse code over code that is complete. The more concise the more elegant, that is as long as it is still readable. However, I'd choose your algorithm above mine if judging completeness. Nice job.
I'd be more concerned about the correctness than about the completeness. If a function is called "random_string" and the strings generated aren't random, then what is the use of completeness?
Of course it also depends on the actual use of the routine, but the original algorithm, however elegant and clever, would not be suitable for "production use" IMHO.