in reply to Re^2: Writing to file with filehandler in variable, scope issue, clobber becomes append
in thread Writing to file with filehandler in variable, scope issue, clobber becomes append

You can tell it to print from the top of the file via the seek command:

seek $fh, 0, 0;

But that won’t clobber the file contents; if the text you print is shorter than the text you are overprinting, the original text will still show up at the end of your newly-printed text. If you really need to erase the file contents before printing, then yes, you can close the filehandle and then re-open it for writing.

Using END isn’t a matter of performance, it’s a means of simplifying and ensuring correctness. It’s simpler, because you don’t have to explicitly call the sub at each exit point in your code; the cleanup code gets called automatically. And suppose you add a third, then a fourth, then a fifth exit point, and somewhere in all that you forget to call the cleanup sub? That’s the sort of bug that can be hard to detect. Better to ensure correctness via code structure than by relying on human memory!

BTW, I should have said that in Perl the preferred way to exit a script abnormally (i.e., indicating failure of some kind) is to throw an exception using die:

open(my $fh, '>', 'file.txt') or die "Cannot open file.txt for writing +.\n";

If the exception isn’t caught, the script will exit, but any END blocks will still be run first.

Hope that helps,

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

  • Comment on Re^3: Writing to file with filehandler in variable, scope issue, clobber becomes append
  • Select or Download Code