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

Dears monks,
how do I empty the contents of a text file in perl,
I have to delete evrything from a file before updating it.
Thanks in advance. Forgot to mention that I am oprning this file in append mode
open HANDLE,">>","/path/to/file" or die "Cannot overwrite file: $!";
Initially at open I need to delete all contents.

Replies are listed 'Best First'.
Re: empty a file
by Nkuvu (Priest) on Jun 27, 2004 at 16:08 UTC
    Short answer: open FILEHANDLE, ">filename.txt" or die "Hork! $!\n";

    Slightly longer answer: Read perldoc perlopentut and then read perldoc -f open

Re: empty a file
by Joost (Canon) on Jun 27, 2004 at 16:09 UTC
      Forgot to mention that I am opeing this file in append mode.
      So I can not open it in write mode.

        perldoc -f truncate

        Ciao, Valerio

        A reply falls below the community's threshold of quality. You may see it by logging in.
Re: empty a file
by l3nz (Friar) on Jun 27, 2004 at 20:03 UTC
    Either you open the file in append mode or you truncate the file. The two thing don't logically go together.

    Why don't you simply open the file in non-append mode? you'd get the same result as truncate plus append.

Re: empty a file
by Scarborough (Hermit) on Jun 28, 2004 at 12:02 UTC
    If you are openning the file using the data and then writting new data to the file the simple way appears to me as follows
    open IN, $file; #do what you need to do close IN; open OUT ">$file"; #print out the data close OUT;