in reply to read from a file and write into the same file

As you're opening for append, the file pointer is positioned at the end, so your while(<FILE>) does not read anything ('cos it's already at EOF). And, as your print FILE ... is in the same loop, it doesn't write anything either, because it doesn't execute at all...

BTW, it's generally a good idea to get into the habit of always error checking with file operations, in particular with open:

my $filename = "test.txt"; open FILE, "+>>", $filename or die "Couldn't open file '$filename': $! +";

Update: In short, what I think you want to achieve (read from the beginning, write at the end?) cannot be done that way, because a file handle does not maintain two file pointers... Alternatingly reading one line then writing (inserting) one line doesn't work either, because the write doesn't shift around the later parts of the file. Rather, it simply overwrites at that position, which typically doesn't work well with text files (due to different line lengths).  To observe the effect try opening with "+<".

Replies are listed 'Best First'.
Re^2: read from a file and write into the same file
by ysth (Canon) on Mar 03, 2008 at 04:01 UTC
    The file pointer is not guaranteed to be anything in particular between the open and the first write, IIRC.

      strace-ing the OP's code (where nothing is being written) shows

      ... open("test.txt", O_RDWR|O_APPEND|O_CREAT|O_LARGEFILE, 0666) = 5 _llseek(5, 0, [57], SEEK_END) = 0 ...

      which I would interpret to mean that the file pointer is positioned.

      (_llseek is a Linux-specific syscall)

        Right, as far as I know you can count on it being at the end (or at least, the end as of the time of the open) even before the first write on linux. But it isn't guaranteed in general by POSIX.