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

I need to open a file, read from it, and write back to it in my script, but the file in question is constantly getting appended to by a different script, and I want to keep it from getting appended to by the other script until I write back to it with this script. I figured I could use flock to lock the file, but is there any way I can both read and write to the same file by the same filehandle? if not, how else would I accomplish this?
  • Comment on How do I get two-way io access on a file?

Replies are listed 'Best First'.
Re: How do I get two-way io access on a file?
by arturo (Vicar) on Apr 06, 2001 at 21:57 UTC

    You can open a file for r/w access by using

    open FH, "+< $filename" or die "Can't open $filename for r/w: $!\n";

    but working with that may drive you nuts (see perldoc -f open for why).

    Consider having your updating script use a working copy, which gets copied over to the file the other processes access when the updating script's done with it (which is essentially what the perldoc recommends).

    Depending on what you're storing in the file, consider using DB_File and its ilk (e.g. SDBM_File), which will let you treat the data like it's in a hash, easy updating.

Re: How do I get two-way io access on a file?
by Albannach (Monsignor) on Apr 06, 2001 at 21:56 UTC
    You can open a file for both read and write using '+<', and I'm guessing you might want to look at truncate also.
Re: How do I get two-way io access on a file?
by jink (Scribe) on Apr 12, 2001 at 23:05 UTC