in reply to Empty File Contnts before writing

The function you seek is... seek

use strict; use warnings; open my $fh, ">", "testing1.txt"; print $fh "stat"; seek $fh, 0, 0; print $fh "stat-updated"; close $fh; system cat => "testing1.txt";
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Replies are listed 'Best First'.
Re^2: Empty File Contents before writing
by Athanasius (Archbishop) on Feb 19, 2013 at 08:01 UTC

    Yes, seek works in this case because the final output is longer than the initial output. But a word of caution is in order. Consider:

    #! perl use strict; use warnings; my $filename = 'test.txt'; open(my $fh, '>', $filename) or die "Cannot open file '$filename' for +writing: $!"; print $fh "The quick brown fox jumped over the unfortunate dog."; seek $fh, 0, 0; print $fh "The final output."; close($fh) or die "Cannot close file '$filename': $!";

    This results in file “test.txt” containing:

    The final output.ox jumped over the unfortunate dog.

    as seeking to the beginning of the file does not erase its existing contents.

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      So I will have to open and close the file agin in order to completely truncate watever is written in previous write attempts?

        There is also a built-in function called truncate that will do what you want.

        $ perl -Mstrict -Mwarnings -e ' > open my $fh, q{>}, q{rubbish} or die $!; > print $fh qq{A longish line of text\n}; > truncate $fh, 0 or die $!; > print $fh qq{Short\n}; > close $fh or die $!;' $ cat rubbish Short $

        Update: Added example code.

        Cheers,

        JohnGG

      Yeah, gotta watch out for those output-oxen. ;-)

        So I need to open and close my file every time I print something to it so that it overwrites the previous print in the file?? Is there any other way coz I would have open and close the file numerous times.