... 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.


In reply to Re^2: Check randomly generated numbers have not been used before by Anonymous Monk
in thread Check randomly generated numbers have not been used before by R3search3R

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.