in reply to Need to Generate Unique String

Simple solution:

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

Replies are listed 'Best First'.
Re^2: Need to Generate Unique String
by tachyon (Chancellor) on Jul 29, 2004 at 12:57 UTC
    $uniquish = time() . $$ . rand;

    ;-)

    cheers

    tachyon

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

      -stvn

        I love the subtle inclusion of a memory reference.


        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
Re^2: Need to Generate Unique String
by hv (Prior) on Jul 29, 2004 at 19:58 UTC

    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

        Then the sleep() should ensure the pid is not reused within the same tick, so it should still remain unique.

        It does depend a bit on the precise sleep() implementation though; possibly safer (and a bit faster) would be:

        my $t = time; select(undef, undef, undef, 0.1) while time <= $t; $unique = "$t$$";

        It also assumes a monotonically increasing time: if the sysadmin may correct a fast clock backwards, it would be very difficult to cope with. (Note that ntpd will adjust the time in increments of less than a second except when the clock error is "large"; once initially synchronised, a running system corrected by ntpd should never normally skip a full second forwards or backwards.)

        Hugo

      Or use a counter:

      { my $cnt = 0; sub unique { return $time() . $$ . $cnt++; } } $unique = unique();