in reply to Trying to substitute a variable with another variable in a string but not working
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Trying to substitute a variable with another variable in a string but not working
by GrandFather (Saint) on Feb 24, 2015 at 23:02 UTC | |
by RonW (Parson) on Feb 25, 2015 at 00:06 UTC | |
by Anonymous Monk on Feb 24, 2015 at 23:23 UTC | |
|
Re^2: Trying to substitute a variable with another variable in a string but not working
by kaushik9918 (Sexton) on Feb 25, 2015 at 02:54 UTC |