This generates session IDs that are unique but of a specific length (32 hex digits), making it ideal for storage in databases. The ID is based on hostname, time, and some psuedo-random data. I've run a test with this to generate 50,000 IDs as fast as possible and check for collisions -- I didn't get any. (Not really a strong test, but good enough for most uses).

Update: I'm seeing a lot of people making the assumption that these are for Web Sessions, or similarly short-life-span situations. I should have been more clear. I'm using these for a database application that is exported to a proprietary application -- so Apache anything is useless for this. Also, some of these sessions involve loading several hundred GB of data and can stay open for days, so lowering collisions over a span of time is important.

Please scan through the replies for specific details.

use strict; use Digest::MD5; use Sys::Hostname; sub md5sid { my $hostname = hostname(); my $serial = new Digest::MD5; $serial->add($hostname); # Having the time in hex form is useful $serial->add(sprintf "%X", time()); # This is sort of slow, but strong. Reducing # the param for rand() will speed things, but # make collisions more likely. for (my $i=1; $i < rand(2345678); $i++ ) { $serial->add(chr(int(rand(223))+32)); } my $session = $serial->hexdigest(); return $session; }#-sub md5sid
The following alternate was suggested by simonm. I haven't personally tested it, but it seems like a Better Way.
use Data::UUID; use constant IDGenerator => Data::UUID->new(); sub new_sid { IDGenerator->create() }
See the Data::UUID module on CPAN.

In reply to MD5-based Unique Session ID Generator by radiantmatrix

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.