Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

How to generate a unique word or number?

( #34563=categorized question: print w/ replies, xml ) Need Help??
Contributed by Anonymous Monk on Sep 29, 2000 at 09:52 UTC
Q&A  > data formatting


Answer: How to generate a unique word or number?
contributed by Adam

$str = time();
Values will be unique, as long as you only need a new number every couple of seconds.

But seriously, if need this for any kind of security purpose, then you want something that isn't predictable either. There was a good discussion of this at Randomizing Unique ID?. I'll boil it down for you:

Don't re-seed (as discussed here). The default seed is very good, in versions of Perl since 5.004.

If you do choose to re-seed, incorporate the previous seed:

srand( rand(~0) ^ $mySeed );

That said, use some combination of time, PID (Process ID, or $$), and rand.

Randomizing Unique ID? also contemplates changing the base of the number (making it a string); this resulted in the Base Conversion Utility.

Unfortunately even this scheme is not perfect. You have a couple issues:

  • How many unique strings are you trying to make?
  • Are they from the same run of the script, or different runs?
    $$ won't change in one run of a script.
  • How often is it run?
    time only provides resolution down to the second.
    It also can go backwards.*
    On Win32 you have Win32::GetTickCount(), but that repeats every month or so.
  • There's a chance, ever so slight, that rand will repeat itself when time and pid have not changed.
If this all occurs within one process, then simply tacking on a counter will guarantee uniqueness.

So the bottom line is, use as much of the output from rand as you can, to reduce the probability of a repeated string.


* Yes, time can go backwards.
"How?"
Well, time uses the system clock, which has a tendency to drift. There are several mechanisms in use to keep the clock right. Some of these methods attempt to return the clock to some standard (UTC) by manually manipulating the drift (changing the number of ticks/sec to get the clock to speed up or slow down). But some systems actually re-set the clock to UTC. If the clock was running fast this re-set will move time backwards.

Answer: How to generate a unique word or number?
contributed by japhy

Here's one way. The sequence of strings it produces is non-repeating, and, though very long, not infinite.

{ my $UNIQ_ID = 'a'; sub next_id { return $UNIQ_ID++ } }
Answer: How to generate a unique word or number?
contributed by clemburg

If you're wanting this for a temporary filename, consider using POSIX::tmpnam or IO::File::new_tmpfile.

If you want a unique name for some sort of data entity, consider using Symbol::gensym instead.

Answer: How to generate a unique word or number?
contributed by spx2

I would approach the problem in a simple manner

sub generate_random_string { my $res = ''; $res.= chr int rand(26)+96 for 1..8; return $res; }
Use this to generate a random string(with 8 letters).
After this you can just use a hash/hashref to assure no new string generated
is a duplicate with a past one

You can do this like this
my $h={}; sub generate_new_unique_random_str{ my $result; while(exists $h->{$result=generate_random_string()}) {}; return $result; }

The code above will store in $result each time the value returned by our
random string generator,and if it is not beeing found in the hash then
the loop terminates and the new generated value is returned
Answer: How to generate a unique word or number?
contributed by hossman

use Data::GUID:

my $word = Data::GUID->new()->as_base64();

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • 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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            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.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others surveying the Monastery: (5)
    As of 2014-08-02 03:22 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      Who would be the most fun to work for?















      Results (54 votes), past polls