While it is possible to modify a file in-place, it is simpler and safer to create a new file, then rename the original with a '.bak' extension, then the new file to the name of the original:

open FILE, '<', $file; my $nfile = $file . '.new'; open OFILE, '>', $nfile; while (<FILE>){ if($_ =~ /STARTING_PATTERN\s+(.*)/){ $sub=$1; s/$sub/$cell_name/ ; } print OFILE, $_; } close FILE; close OFILE; rename $file, $file . '.bak'; rename $nfile, $file;

Note that while (<FILE>) is just a short cut for while ($_ = readline(FILE)) so $_ contains a copy of the line as it exists in the file. Any modifications to $_ affect only $_, not the file. In your code, you made a further copy, $string, so you were modifying a copy of a copy.

Modifying a file in-place is tricky to get right even when simply replacing existing bytes. If you are inserting or deleting bytes (which may happen when modifying characters using a variable length encoding like UTF-8), it is a lot trickier.


In reply to Re: 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.