Hello Friends Today, through this tutorial, I will tell you generate a 4-digit random number in Perl.
Here’s how to generate a 4-digit random number in Perl:
use strict; use warnings; # Generate a random floating-point number between 0 (inclusive) and 1 (exclusive) my $random_float = rand(); # Multiply by 10000 and cast to integer to get a 4-digit number my $random_number = int($random_float * 10000); # Print the random number print "$random_number\n";
Explanation.
1. `use strict;` and `use warnings;` are good practices to enable stricter code and catch potential errors.
2. `rand()` generates a random floating-point number between 0 (inclusive) and 1 (exclusive).
3. Multiplying by `10000` scales the random number to a range between 0 and 9999.9999.
4. Casting to an integer using `int()` removes the decimal part, resulting in a 4-digit integer.
5. Finally, the generated `$random_number` is printed.