I am running the following code to open a file (test) and edit(search and replace) it. Program seems to open the file but instead of replacing it deletes everything in the file. I am not sure why that is happening. Can anyone help me out here?
#!use/bin/perl
use strict;
use warnings;
my $line = $ARGV[0];
my $find = '\s{6}seqfile\s=\sinfile';
my $replace = '\s{6}seqfile\s=\sinfil2';
open (FILE, ">/home/shubhi/Desktop/pamlrun/test") || die "cant open file \n";
my @body = <FILE>;
foreach $line(@body)
{
(s/$find/$replace/g);
{
print FILE "$line";
}
}
close(FILE);
print "reached here\n";
exit;
Your open() is opening a file handle to write to your file. Replace
with
In the code you’ve posted, it immediately creates this file for output only. You should open the file, read/process the contents, and then write it out. If the file is sizable, then write to a new file as you read the old one, and replace the old one upon (successful) completion.