in reply to Re: Need to Generate Unique String
in thread Need to Generate Unique String

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

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

Hugo

Replies are listed 'Best First'.
Re^3: Need to Generate Unique String
by BrowserUk (Patriarch) on Jul 29, 2004 at 21:08 UTC

    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

Re^3: Need to Generate Unique String
by ccn (Vicar) on Jul 29, 2004 at 20:04 UTC

    Or use a counter:

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