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;

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!

/usr/bin/perl -p -i -e "s/freind/friend/g" filename

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.