0

Hi,

I am trying to open a file and correct the spelling of friend. But when I open the file test.txt again it is all blank.

my $opened = open(MYFH , ">test.txt");

my $line;
my $lnum = 1;
while( $line = <MYFH> ){
  print "$lnum: $line\n";
 $line =~  s/freind/friend/g;
 print MYFH "$line";
  $lnum++;
}
close MYFH;
3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by anuragmathur1
0

Hi techie929,

I *think* that you are getting an empty file because you are opening the file with ">", which will create a file if one does not exist, or *truncate* the file if it does exist. Therefore, the file is being truncated before you even get to read it into the rest of your script.

If you open it with "+<", you'll be able to read and write the existing file, but the problem with your *current* script is that you'll probably end up with each line being doubled.

You might want to think about *reading* from your input file, and *writing* the output to a second file (the perl -i "in-place" option might be a possibility as well...)

I hope this helps!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.