http://www.perlmonks.org?node_id=1019564


in reply to Re^2: Empty File Contents before writing
in thread Empty File Contnts before writing

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

Replies are listed 'Best First'.
Re^4: Empty File Contents before writing
by gautamparimoo (Beadle) on Feb 20, 2013 at 05:43 UTC

    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.

      No, you can use truncate and seek and if you put them together in a subroutine you only have to make one call each time to empty your file ready for the next print statement. Note that /usr/bin/hexdump run on an empty file produces no output.

      $ perl -Mstrict -Mwarnings -e ' > sub truncZero > { > my $fh = shift; > truncate $fh, 0 or die $!; > seek $fh, 0, 0 or die $!; > } > > open my $fh, q{>}, q{rubbish} or die $!; > > print $fh qq{Mary had a little lamb\n}; > print qx{/usr/bin/hexdump -vC rubbish}, qq{-----\n}; > > truncZero( $fh ); > print qx{/usr/bin/hexdump -vC rubbish}, qq{-----\n}; > > print $fh qq{The boy stood on the burning deck\n}; > print qx{/usr/bin/hexdump -vC rubbish}, qq{-----\n}; > > truncZero( $fh ); > print qx{/usr/bin/hexdump -vC rubbish}, qq{-----\n}; > > print $fh qq{I met a traveller from an antique land\n}; > print qx{/usr/bin/hexdump -vC rubbish}, qq{-----\n}; > > close $fh or die $!;' 00000000 4d 61 72 79 20 68 61 64 20 61 20 6c 69 74 74 6c |Mary had +a littl| 00000010 65 20 6c 61 6d 62 0a |e lamb.| 00000017 ----- ----- 00000000 54 68 65 20 62 6f 79 20 73 74 6f 6f 64 20 6f 6e |The boy s +tood on| 00000010 20 74 68 65 20 62 75 72 6e 69 6e 67 20 64 65 63 | the burn +ing dec| 00000020 6b 0a |k.| 00000022 ----- ----- 00000000 49 20 6d 65 74 20 61 20 74 72 61 76 65 6c 6c 65 |I met a t +ravelle| 00000010 72 20 66 72 6f 6d 20 61 6e 20 61 6e 74 69 71 75 |r from an + antiqu| 00000020 65 20 6c 61 6e 64 0a |e land.| 00000027 ----- $ cat rubbish I met a traveller from an antique land $

      I hope this is helpful.

      Cheers,

      JohnGG