Hello,
I want to open a file, find a target string, then change the string to something else, and finally save the file. The code opens the file with ">+". However, rather than modifying the string in place, it adds another line. I wonder what is the right syntax. Here is an example of what I want to do:
===== the file: text.txt =====
parameters tmp=95
This file should be changed to
====== after the Perl script =====
parameters tmp=27
Nothing else should be changed after running the script. The script is as follow. It adds another line, which is not what I want.
I want to open a file, find a target string, then change the string to something else, and finally save the file. The code opens the file with ">+". However, rather than modifying the string in place, it adds another line. I wonder what is the right syntax. Here is an example of what I want to do:
===== the file: text.txt =====
parameters tmp=95
This file should be changed to
====== after the Perl script =====
parameters tmp=27
Nothing else should be changed after running the script. The script is as follow. It adds another line, which is not what I want.
Code:
$temp = 95;
$newtmp = 27;
$file = "text.txt";
open(FILE, "+< $file") or die "no file has been opened";
@contents = <FILE>;
foreach(@contents) {
if(/parameters tmp=(\d+)/) {
if ($1==95) {
s/$1/$newtmp/eg;
print FILE $_;
}
}
}
close(FILE);