Reputation: 189
I want to replace some string in a file and save it back. I have already code which can open the file, find the string and replace it. But file is not getting saved. What is wrong with it?
open MYINPUTFILE, $EventLog;
my @lines = <MYINPUTFILE>; # read file into
my @errors = ();
my $size = $#lines + 1;
for ($i = 0; $i < $size; $i++) {
if ($lines[$i] =~ m/$s1(.*)$s2/) {
$lines[$i] =~ s/$s1(.*)$s2/$s1.($1+4).$s2/eg;
print $lines[$i] ;
}
}
close MYINPUTFILE;
Upvotes: 0
Views: 145
Reputation: 69264
There's good advice about this subject in the Perl FAQ.
How do I change, delete, or insert a line in a file, or append to the beginning of a file?
Upvotes: 0
Reputation: 13792
Your script opened the file in read mode, and printed to STDOUT. You need to open a second temporary file, write the changed output to it. And finally, remove the first file and rename the temporary file as your final file.
Also, I'd do this:
Replace FILEHANDLES:
open my $input_file, '<', $EventLog or die $!;
Don't read the whole file into a array (it's a bad idea for huge files). Read line by line and handle it properly:
while( my $line = <$input_file> ) {
#...
}
Upvotes: 1