How to Generate 6 Digit Random Number Perl?

Hello Friends Today, through this tutorial, I will tell you how to generate a 6 digit Unique random number in Perl.

Here are two ways to generate a 6-digit random number in Perl:

Method 1: Using `rand()` and string manipulation.

use strict;
use warnings;

sub generate_six_digit_number {
# Generate a random integer between 100000 and 999999 (inclusive)
my $random_number = int(rand(900000)) + 100000;

# Convert the integer to a string
my $string_number = sprintf("%06d", $random_number);
return $string_number;
}

# Example usage
my $number = generate_six_digit_number();
print "Generated 6-digit number: $number\n";

Explanation-

1. The `generate_six_digit_number` subroutine uses `rand()` to generate a random floating-point number between 0 and 1.
2. We use `int` to convert it to an integer.
3. To ensure the number is within the desired range (100000 to 999999), we add 100000 to the random number.
4. The `sprintf` function is used to format the integer into a string with 6 digits and leading zeros if necessary.
5. The subroutine returns the formatted string.

Method 2: Using `List::Util::shuffle` and string manipulation.

use strict;
use warnings;
use List::Util qw(shuffle);

sub generate_six_digit_number {
# Create an array of digits 0-9
my @digits = (0..9);

# Shuffle the array randomly
shuffle(@digits);

# Join the first 6 digits into a string
my $number_string = join("", @digits[0..5]);
return $number_string;
}

# Example usage
my $number = generate_six_digit_number();
print "Generated 6-digit number: $number\n";

Explanation:-

1. The `generate_six_digit_number` subroutine creates an array `@digits` containing all digits from 0 to 9.
2. It uses `shuffle` from the `List::Util` module to shuffle the elements randomly.
3. It then joins the first 6 elements (representing the first 6 digits) of the shuffled array into a single string using `join`.
4. The subroutine returns the generated 6-digit string.

Both methods are valid and achieve the same goal. Choose the method that best suits your preference and coding style.