Reputation: 909
I have a file letters.txt
which has couple letters
@string1 10 letters
A H K Y M H O L H L
@string2 9 letters
H N U P W X L Y H
I am trying to create a file which will have random numbers from 20 to 60 for each letter, for each string.
My expected output should look like :
@string1
29 27 56 43 39 40 36 48 59 38
@sting2
26 36 39 39 26 51 38 42 42
I have tried the code below with $minimum
as 20 and $maximum
as 60:
open ($fh, '>', $fileToLocate) or die;
my $x = $minimum + int(rand($maximum - $minimum);
print $fh "$x\n";
close $fh;
It creates only one random number in $fileToLocate
file.
I want to extract the number of letters in each string — written just before letters
in the input file: 10 for @string1
and 9 for @string2
I have tried to this code to create 30 random numbers ranging between 20 and 60, however it did not work out
my @Chars = ( 20 .. 60);
$RandString = join("", @Chars[ map { $x } ( 1 .. 30 ) ]);
print $fh "$RandString\n";
close $fh;
Upvotes: 1
Views: 943
Reputation: 164679
You're close.
The code to pick a random number from $min
to $max
looks like this.
my $rand = $min + int rand($max - $min + 1));
So you had that part right, but with an off-by-one error (I made the same mistake earlier). Because rand
starts at 0, int rand $x
will go from 0 to $x - 1
.
Then you need to generate a bunch of them. You're close with the map, but $x
only stores a single random number, so map { $x } ( 1 .. 30 )
will just give you one number repeated 30 times. Instead you need to get a new random number inside the map block.
my @rands = map { $min + int rand($max - $min + 1)) } 1..length $string;
That will run int($x + rand($y-$x))
for a number of times equal to the number of characters in $string
and put them all into the list @rands
. Then you can join @rands
like you have already.
print $fh join '', @rands;
That should get you the rest of the way.
Upvotes: 4