John W. Krahn wrote:
Flemming Greve Skovengaard wrote:
Travis Thornhill wrote:
I need to make strings of variable length for testing inputs.
The strings can contain any letter, say 'a', and I need to be able
to create the string with
255, 256 or any length.
Is there a quick and easy way to do this with perl?
This will generate a string of random length between 1 and 256 with random
letters from a to z.
I have only tested it lightly, so the best of luck to you.
use strict;
use warnings;
my ($rand_string, $index);
$index should be declared inside the for loop, not at file scope.
Yes, my mistake.
my @letters = qw( a b c d e f g h i j k l m n o p q r s t u v w x y z );
Could be shortened to:
my @letters = 'a' .. 'z';
I knew there was a way to do with the range operator, but I kept drawing
a blank.
my $length = int rand( 255+1 );
Why not just rand( 256 )?
I meant to write:
int rand( 256+1 )
That would produce a number between 1..256 instead of 0..255.
Or at least it should according to how I understand rand() to work.
for (1..$length) {
$index = int rand(scalar @letters-1);
You have an off-by-one error. The letter 'z' will never be picked.
Yes, I see that now. But I did write "lightly tested".
$rand_string .= $letters[$index];
Or simply:
$rand_string .= $letters[ rand @letters ];
Yes, that would save a line of code, a variable and a call to scalar().
But shouldn't that be:
$rand_string .= $letters[ int rand @letters ];
instead?
}
print $rand_string, "\n";
You could write that on one line as:
my $rand_string = join '', map $letters[ rand @letters ], 1 .. $length;
Ahh, the oneliner. Something that almost always takes me longer to make
than a small multiline script.
John
--
Flemming Greve Skovengaard The figure stands expressionless
a.k.a Greven, TuxPower Impassive and alone
<[EMAIL PROTECTED]> Unmoved by this victory
4011.25 BogoMIPS And the seeds of death he's sown
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/