On Nov 22, 4:27 pm, carni...@gmail.com (Mark Wagner) wrote: > I want to update a status file, similar to this: > > open OUTFILE, ">", "status.txt"; > print OUTFILE "$last_date\n"; > close OUTFILE; > > However, if something goes wrong (e.g. the disk is full), this code > will replace "status.txt" with an empty file. How can I update the > file while preserving the previous contents if something goes wrong? > > -- > Mark Wagner
Have you considered appending? See an example below, with 2 successful status messages and 1 failed one. The advantage of this is that you do not try to overwrite anything - you just add. Note lexical filehandles and the use of autodie to automatically check for errors. $ rm -f status.txt $ perl -e 'use autodie qw(:all); open my $status_fh, q{>>}, "status.txt"; print {$status_fh} scalar(localtime) . "\n"; close $status_fh;' $ cat status.txt Tue Nov 22 18:22:29 2011 $ perl -e 'use autodie qw(:all); open my $status_fh, q{>>}, "status.txt"; print {$status_fh} scalar(localtime) . "\n"; close $status_fh;' $ cat status.txt Tue Nov 22 18:22:29 2011 Tue Nov 22 18:22:44 2011 $ chmod a-w status.txt $ perl -e 'use autodie qw(:all); open my $status_fh, q{>>}, "status.txt"; print {$status_fh} scalar(localtime) . "\n"; close $status_fh;' Can't open 'status.txt' for appending: 'Permission denied' at -e line 1 $ cat status.txt Tue Nov 22 18:22:29 2011 Tue Nov 22 18:22:44 2011 $ HTH, Timur Shtatland -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/