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

I know how to open a file for read and write, but I'm not sure how you actually do both to the file? In my script I basically print to a file then read what I wrote later (because I want to avoid a giant memory buffer). How to do this without having to close the close the file descriptor then reopen for read? Thanks

Replies are listed 'Best First'.
Re: Both read and write to file
by zentara (Cardinal) on Aug 23, 2011 at 18:54 UTC
Re: Both read and write to file
by roboticus (Chancellor) on Aug 23, 2011 at 18:15 UTC

    stevensw:

    Generally you use seek to move the file descriptor to the specified location and perform your read or write. If you want to remember where you are in the file (so you can return to it later), use tell. The docs on seek will give you some example.code.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: Both read and write to file
by blue_cowdawg (Monsignor) on Aug 23, 2011 at 19:19 UTC

    You could use Tie::File which would allow you to tread the file as if it were an array... just a thought...


    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg
Re: Both read and write to file
by locked_user sundialsvc4 (Abbot) on Aug 24, 2011 at 12:35 UTC

    Another strategy is File::Map, which maps a view of the arbtrarily-large file into your process’ memory space.   The file itself now serves as a “buffer,” because what is actually happening is that, when virtual-memory page faults happen in this area of the process storage space, they are resolved by the operating system as direct accesses (by the operating system, on your behalf...) to that file.