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

I have a text file that I need to re-initialize, meaning I need to empty it's contents but not unlink the file itself. Is there a more elegant way of doing it besides what I have below?
open(FILE, ">file.dat"); close FILE

Replies are listed 'Best First'.
Re: Empty a text file?
by kyle (Abbot) on Apr 11, 2008 at 18:16 UTC

    You could do it with more error checking.

    my $file = 'file.dat'; open my $fh, '>', $file or die "Can't write '$file': $!"; close $fh or die "Close error: $!";

    You could do it with a call to the shell. (If 'file.dat' is not really a literal, you have to watch out for shell metacharacters in the filename.)

    system( "echo -n > file.dat" );

    Or you could just use truncate:

    truncate 'file.dat', 0 or die "Can't truncate file.dat: $!";
      OT, but FYI:

      If you're using that second one under Linux (under bash on Linux at least) then you're wasting a call to echo. This will work just as well:

      perl -e 'system q{>file.dat}'
Re: Empty a text file?
by sasdrtx (Friar) on Apr 11, 2008 at 18:18 UTC
    Yes. Try
    open FILE, ">file.dat"; close FILE
    I admit it's not a *lot* more elegant, but what do you expect?
    sas