dee00zee has asked for the wisdom of the Perl Monks concerning the following question:

I understand that we can read and write to the same
file using +> operator.
I try it but it didn't work.
example:
open(IN,"+>file1");
could somebody please help me

Replies are listed 'Best First'.
Re: read and write to the same file
by si_lence (Deacon) on Oct 26, 2004 at 07:01 UTC
    Hi,
    To open a file in update mode you should use
    open(FH, "+< file1) or die "Opening: $!";

    si_lence
Re: read and write to the same file
by gaal (Parson) on Oct 26, 2004 at 07:02 UTC
    What didn't work? Did open succeed? You should be using the '... or die "open failed: $!"' idiom to check that.

      I think what he means is that if you do and open like +> you get RW access BUT you have stomped on the original file (if it existed). +>> is OK as is +<

Re: read and write to the same file
by archen (Pilgrim) on Oct 26, 2004 at 14:10 UTC
    Just to elaborate a bit more on what tachyon said: When you open a file for write you use ">file". This will destroy the contents of "file" if it already existed and you will be able to write to the file. ">" still works the same way even if you add read support, and I'm pretty sure the perl documentation warns about what you ended up doing ("+>"): opening the file for read and write, but destroying the contents before you got a chance to read.

    What you want is "+<". You can now read and write to the file, but you will want to familiarize yourself with the seek command, which will allow you to write to different spots in the file.

    Also keep in mind that the file does not truncate itself. For instance if you have a file that contains "oooo", you seek to the beginning of the file and write "XXX", your file will contain "XXXo".