Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

overwriting a file

by Anonymous Monk
on Oct 30, 2007 at 10:59 UTC ( #647995=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks

I have a question that I believe must have an obvious answer, but I'm not perl-savvy enough to think of it. I'm lazy, impatient and full of hubris too. (But I have had a look through the tutorial and Q&A sections).

I have a text file that I want to automatically update at regular intervals. Sometimes the number of lines that need to be written to the file is smaller than the number of lines already existing in the file, with the result that some of the lines from the old version of the file are still present after I've over-written it. Is there any way of getting rid of these old,unwanted lines?

(At the moment, I'm just using a simple set of write instructions:

open OUTPUTFILE, ">$outputfile" or die "Couldn't open output file: $!" +; print OUTPUTFILE "blah blah blah"; close OUTPUTFILE;



Replies are listed 'Best First'.
Re: overwriting a file
by Sidhekin (Priest) on Oct 30, 2007 at 11:15 UTC

    As long as you open the file with mode >, the old contents should be gone already.

    Assuming you are opening with mode +>, +< or similar (for read/seek/write combos, particularly useful with file locking), this is a real problem, and the solution you are looking for is truncate, probably with tell:

    truncate( OPENFILE, tell(OPENFILE) );

    (Alternatively, if you can safely truncate to 0 before you even start writing, that might be clearer.)

    print "Just another Perl ${\(trickster and hacker)},"
    The Sidhekin proves Sidhe did it!

Re: overwriting a file
by swampyankee (Parson) on Oct 30, 2007 at 11:40 UTC

    As moritz and Sidhekin said, open HANDLE, "> $filename" should clear the file. Either there is something wrong with your version of Perl (very unlikely, as open is very heavily used) or there's something going on in the code which you're not telling us (much more likely). Try stripping down the code to the least amount that shows the odd behavior that you're reporting and posting it here or in your scratchpad.


    Information about American English usage here and here.

    Any Northeastern US area jobs? I'm currently unemployed.

Re: overwriting a file
by moritz (Cardinal) on Oct 30, 2007 at 11:09 UTC
    I don't think that should happen... You could unlink the file first, just to be sure.

    BTW more infos on the file opening modes can be found in perlopentut

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://647995]
Approved by moritz
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2018-05-25 10:13 GMT
Find Nodes?
    Voting Booth?