0

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;
0

2 Answers 2

1

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> ) {
   #...
}
Sign up to request clarification or add additional context in comments.

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.