How to read and write a text file and put it in the same file? I tried but I got empty files.
My code is :
#!/opt/lampp/bin/perl
print "Content-Type : text/html\n\n";
$ref = '/opt/lampp/htdocs/perl/Filehandling/data_1.txt';
open(REF, "+<", $ref) or die "Uable to open the file $ref: $!";
while (<REF>) {
if($_=~ m/Others/gi) {
$_ =~ s/Others/Other/gi;
print "$_\n";
}
}
$ref = '/opt/lampp/htdocs/perl/Filehandling/data_1.txt';
open(REF, "+>", $ref) or die "Uable to open the file $ref: $!";
print REF "$_\n";
close REF;
close REF;
The
-ioption edits a file in-place, i.e. overwrites the file with the new contents.The
s///operator doesn’t substitute anything if there is no match, so you don’t have to check withm//if you have a match before attempting a substitution.The flow control in your script is flawed; you open for reading, then print to standard output (not back to the file), then open for writing, but don’t write anything useful (or, well, only the last line you read in the input loop).
What’s with the
Content-Type:header, do you want to run this as a CGI script? That sounds like a security problem.Do you only want to print if there is a substitution? If so, try this:
Notice the change from
-pwhich adds a read-and-print loop around your script, to-nwhich only reads, but doesn’t print your file.