Sri
Sri

Reputation: 177

Cannot read from a file opened in read/write/append mode

Here is my code

use strict;
use warnings;

open(INFILE,"<File1")    or die "Can't open the file";
open(OUTFILE,"+>>File2") or die "Can't open the file";

while(<INFILE>) {
   print OUTFILE "$_";
}

while(<OUTFILE>) {
   print "$_\n"; 
}

Am trying to move the contents of File1 to File2 which is created in read,write and append mode. The problem here is I have my File2 created with File1 contents, but the print statement inside the while(<OUTFILE>) {} is not printing the contents of File2. Anyone help me understand what is wrong here!(I might be making a silly mistake)

Upvotes: 0

Views: 173

Answers (2)

toolic
toolic

Reputation: 62105

After your first while loop, you are at the end of the OUTFILE. So, the second while loop is never really executed. Use seek before you read OUTFILE:

use strict;
use warnings;
open(INFILE,"<File1")or die "Can't open the file";
open(OUTFILE,"+>>File2")or die "Can't open the file";
while(<INFILE>)
{
print OUTFILE "$_";
}

seek OUTFILE, 0, 0;

while(<OUTFILE>)
{
    print "$_\n"; 
}

Upvotes: 5

Ted Bear
Ted Bear

Reputation: 117

Set the cursor back to the start of OUTFILE:

seek OUTFILE, 0, 0;

Upvotes: 3

Related Questions