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

hi,

If we have opened a file and stored something.how do we make changes in that file?

Title edit by tye as single-word titles complicate future searches

Replies are listed 'Best First'.
Re: files
by dmmiller2k (Chaplain) on Mar 18, 2002 at 05:10 UTC

    Regrettably, this is a problem in any language, not necessarily restricted to Perl.

    The short answer is, "it depends."

    A slightly longer answer is, "read in the file, make approporate changes in memory, and write to a new file, then rename both files when you're done." This approach presumes much about the type of file, what kind of changes you're making, how big the file is, and how much of it you're changing (also where in the file). There are an effectively infinite number of things you might be using the file for and ways you might be using it.

    A better anwer to your specific question would be contingent upon more details, including (of course) a code snippet of what you already have done.

    dmm

    If you GIVE a man a fish you feed him for a day
    But,
    TEACH him to fish and you feed him for a lifetime
open for r/w?
by RMGir (Prior) on Mar 18, 2002 at 12:26 UTC
    Like dmmiller2k, I'm not too sure what you're trying to do. If you need to read and write from the file, you can open it in r/w mode by adding a "+" before the file name in your open statement.

    For example:

    $ perl -e'open(X,"+>x.x") or die "cannot open x.x, error $!\n"; print +X "Hi Mike!\n"; seek X,0,0; print X "No";' $ cat x.x No Mike!

    Note the "+>" before the x.x filename. That means "open it for output, but allow read and write". That would clobber an existing file.

    If you want to r/w a file that's already there, use "+<".

    The "seek" command moves the current position back and forth in the file, "pointing" to where you want to read or write from next. You should have a seek any time you switch from reading to writing.

    Hope this helps!
    --
    Mike