EchoAngel has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, what can I do to generate an unique string/number. I would be interfacing with another program and I must somehow generate Unique Ids (string or numbers). I was thinking of using the unix 'date' command but if my perl script runs fast enough. It might take duplicates of the date. Any ideas?

Replies are listed 'Best First'.
Re: Need to Generate Unique String
by Joost (Canon) on Jul 29, 2004 at 12:27 UTC
Re: Need to Generate Unique String
by adrianh (Chancellor) on Jul 29, 2004 at 12:27 UTC
Re: Need to Generate Unique String
by inman (Curate) on Jul 29, 2004 at 12:32 UTC
    Take a look at Data::UUID.

    From the POD:

    This module provides a framework for generating UUIDs (Universally Unique Identifiers, also known as GUIDs (Globally Unique Identifiers). A UUID is 128 bits long, and is guaranteed to be different from all other UUIDs/GUIDs generated until 3400 CE.

Re: Need to Generate Unique String
by borisz (Canon) on Jul 29, 2004 at 12:25 UTC
    Perhaps gettimeofday is enough.
    perl -MTime::HiRes -le 'print join "",Time::HiRes::gettimeofday for (1 +..10)' __OUTPUT__ 1091103638899022 1091103638899336 1091103638899454 1091103638899566 1091103638899679 1091103638899787 1091103638899897 1091103638900006 1091103638900115 1091103638900239
    Boris
Re: Need to Generate Unique String
by eserte (Deacon) on Jul 29, 2004 at 12:18 UTC
    With Time::HiRes::gettimeofday you have microseconds resolution.
Re: Need to Generate Unique String
by ccn (Vicar) on Jul 29, 2004 at 12:33 UTC

    Simple solution:

    $unique = time() . $$ . rand;

      $uniquish = time() . $$ . rand;

      ;-)

      cheers

      tachyon

        use Digest::MD5; $pretty_darn_close_to_unique = md5_hex(md5_hex(time() . $$ . rand . {} +));

        -stvn

      You can get guaranteed uniqueness by replacing the rand call with a "hold this pid until the time changes":

      $unique = time() . $$; sleep 1;

      Hugo

        Guarenteed with a given process, but if multiple copies of the process are running, with time() limited to 1 second resolution?


        Examine what is said, not who speaks.
        "Efficiency is intelligent laziness." -David Dunham
        "Think for yourself!" - Abigail
        "Memory, processor, disk in that order on the hardware side. Algorithm, algoritm, algorithm on the code side." - tachyon

        Or use a counter:

        { my $cnt = 0; sub unique { return $time() . $$ . $cnt++; } } $unique = unique();
Re: Need to Generate Unique String
by Jaap (Curate) on Jul 29, 2004 at 12:14 UTC
    Do you have a chance to view all the other/previous UID's? Then take the higest one and ++ it.