in reply to Re: Check randomly generated numbers have not been used before
in thread Check randomly generated numbers have not been used before

... I quite frankly would not bother to check for it.

R3search3R said the check is to avoid duplicate part numbers, and didn't say how many numbers they're generating, so that advice seems very wrong.

R3search3R: Why aren't you using a real database for this? Here's a solution based on your approach, but note that if the list is long and this is run often, it's horribly inefficient because it reads the entire file every time it's run.

use warnings; use strict; use diagnostics; my $database = "Database.txt"; my $part_number_range = 10; open (my $input, "<" , $database) || die "Can't open $database: $!"; my %part_numbers = map { chomp; $_=>1 } <$input>; close $input; use Data::Dumper; print Dumper(\%part_numbers); # DEBUG my $new_part_number; my $bail_out_count; while (1) { $new_part_number = sprintf("%07d", int(rand($part_number_range))); last unless exists $part_numbers{$new_part_number}; die "Bailing out after too many retries" if ++$bail_out_count>1000 +; print "Collision with part number '$new_part_number', retrying\n"; + # DEBUG } print "Chose part number: '$new_part_number'\n"; # DEBUG open (my $output, ">>" , $database) || die "Can't open $database: $!"; print $output "$new_part_number\n"; close $output;

Note that you'll probably want to change the values of $database and $part_number_range, and remove the statements marked with # DEBUG after testing.