Different definition of "in place".

Per perlrun, setting $^I is like including the -i option on the command line. From perlrun:

specifies that files processed by the <> construct are to be edited in-place. It does this by renaming the input file, opening the output file by the original name, and selecting that output file as the default for print() statements. The extension, if supplied, is used to modify the name of the old file to make a backup copy

So setting $^I = '.bak' has the same effect as my code. Minor difference: My code reads the original, writes the new, then renames both files. Setting $^I causes the original to be renamed first.

The "in place" I was referring to is, literally, modifying the existing file where it is stored1. This can be done through careful use of tell and seek. The following should work when replacing existing bytes:

open my $fh, '<+:raw', $file; # raw so file is read/written in bytes, +not characters my $where = tell($fh); while (<$fh>) { ...; # modify 1 or more bytes seek $fh, $where, SEEK_SET; print $fh, $_; $where = tell($fh); } close $fh;

If attempting to add or delete bytes, more work needs to be done.

---

1 This ignores the possibility that the underlying storage manager/controller could write the modified blocks of the file to different locations in storage, then update the file's "block map" after the write is successfully completed.


In reply to Re^3: Trying to substitute a variable with another variable in a string but not working by RonW
in thread Trying to substitute a variable with another variable in a string but not working by kaushik9918

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.