What I want to achieve is editing a file in-place (via a temporary file) and optionally creating a backup file as well if a backup filename is given.

My idea was therefore to use the backup file as the temporary file, where a backup filename is given, or else use File::Temp to create one for me. I then copy to the temporary file, read from it and write back over the original, and then leave File::Temp to clean up the temporary file if one was created. (If a specified backup file was used instead, then it gets left afterwards, of course.)

I could start by renaming the original to the backup/temporary name instead, as you suggest, but where do I get the temporary name from? File::Temp returns an open filehandle - no good for renaming my original file to, hence I was looking to copy to it instead.

Actually, having read Re-runnably editing a file in place, I'm now thinking something along those lines would be better:

I could get a temporary filehandle, read from the original file, process the data and write to the temporary filehandle. Then I'd want to rename the temporary file to the original filename, but I don't know the temporary filename unless I ignore File::Temp's advice and pick up both the handle and the name. Maybe that's safe enough since I wouldn't be doing anything with the temporary filename except renaming it (and I therefore wouldn't want File::Temp to try to delete the temporary file either). (I'd have to create the backup file separately, rather than using it as the temporary file, in this scheme, of course.)

- Steve


In reply to Re^2: Copying a file to a temporary file by shay
in thread Copying a file to a temporary file by shay

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.