I want to edit a file "in place", preserving the file's permissions, yet be safely re-runnable should an interruption occur at any time. Though the script does not need to be multi-user safe, I am vaguely interested in how that might be achieved (I guess with file locking). I know about Perl's -i switch, but this switch first renames the file, so if the user CTRL-C's (or power is lost) after the rename but before the new file is written, the script is not re-runnable because the original file has been renamed (or may not be complete). Is that right? Anyway, here is my attempt at solving this problem.

# Slurp file $fname into array @lines. open(my $fh, $fname) or die "open '$fname': $!"; my @lines = <$fh>; close($fh); # Mangle @lines as appropriate ... if ($file_contents_changed) { my $bak = $fname . $$ . '.tmp'; open(my $fh, '>'.$bak) or die "create $bak: $!"; print $fh @lines or die "writing $bak: $!"; close($fh) or die "close $bak: $!"; defined(my $mode = (stat($fname))[2]) or die "stat $fname: $!"; -w _ or (chmod($mode|0200, $fname) or die "chmod $fname: $!"); rename($bak, $fname) or die "rename $bak $fname: $!"; chmod($mode, $fname) or die "chmod $fname: $!"; }

This has at least one flaw. In the case of a read-only file, if you are interrupted after chmod($mode|0200) but before chmod($mode), the file $fname will have the wrong permissions on re-run. Improvements welcome.

References Added Later


In reply to Re-runnably editing a file in place by eyepopslikeamosquito

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.