All of these solutions using -e are introducing a race condition(*) into your code. If you can guarantee there's only ever going to be a single instance of this running at any given time, you might decide that's OK and live dangerously.

If you can't (or you're sufficiently paranoid to do it correctly the first time :), you need to look at using sysopen and the O_EXCL flag. You keep trying to open filenames until one succeeds, then you go on and write into it. See also perlopentut for examples using sysopen in this way.

(*) The race condition is that your test for the file's existence and the opening of the filename aren't a single, atomic action. It's entirely possible that two separate processes could check for the existence of the same filename simultaneously and both think they both can write to the same "unique" filename. Using sysopen and O_EXCL makes the test-and-open a single action which either succeeds or fails as one. Many security holes can be traced back to race conditions; do it right the first time and avoid them to begin with.


In reply to Re: unique filename by Fletch
in thread unique filename by lax

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.