I'm writing a script that archives mail messages for my entire site. Thus, the volume could potentially be pretty high. This script is called from a .forward file, one invocation per message. I do some processing on each message (mainly deciding whether or not to archive it). If I do archive the message, I write it to a file (one file per message). My question is what is the best way to avoid filename collisions? Right now I generate a name for each message file like this:
use Time::HiRes qw(gettimeofday); use POSIX qw(strftime); my $ArchiveDir = "/tmp/archive/"; ( -w $ArchiveDir ) or die "archive dir $ArchiveDir not writable"; # Get the number of microseconds. (undef, $usec) = gettimeofday; # Now create the archive filename and open that file. Use # sub-second resolution for name to make sure it's unique. $ArchiveFile = strftime "%Y%m%d%H%M%S", localtime; # make sure we get the full 6 digits on microseconds. $ArchiveFile .= "." . sprintf("%06d",$usec); # Combine $ArchiveDir with the filename. $ArchiveFile = $ArchiveDir . $ArchiveFile; # open the file. open(ArchiveFH,">$ArchiveFile") or die "failed to open ArchiveFile: $!";
So this creates files of the format 20050502133658.410018. Now to anticipate several questions: Now since I'm using microseconds here, it seems highly unlikely that two of my archive files could get the same name. But is it technically possible? What is the best way to generate unique files? Should I be using File::Temp? One annoyance with that is it enforces certain constraints on the filename.

In reply to What's the best way to avoid name collisions when creating files? by philiph

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.