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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |