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,


In reply to Re^3: Writing to file with filehandler in variable, scope issue, clobber becomes append by Athanasius
in thread Writing to file with filehandler in variable, scope issue, clobber becomes append by Marcool

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.