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.
> 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';
> my $length = int rand( 255+1 );
Why not just rand( 256 )?
> for (1..$length) {
> $index = int rand(scalar @letters-1);
You have an off-by-one error. The letter 'z' will never be picked.
> $rand_string .= $letters[$index];
Or simply:
$rand_string .= $letters[ rand @letters ];
> }
>
> print $rand_string, "\n";
You could write that on one line as:
my $rand_string = join '', map $letters[ rand @letters ], 1 .. $length;
John
--
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order. -- Larry Wall
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/