Simply open the file for writing (not appending) and write out the entire file. This is the easiest way to do it:
# file opened, read into $my_data, closed, and $my_data modified appro +priately { local *OUTPUT; open(OUTPUT, "> filename_here") || die "Can't open output file: $! +"; print OUTPUT $my_data; close(OUTPUT) || die "Can't close my file: $!"; }
A few comments. The curly braces give us a block scope for the local filehandle OUTPUT. If OUTPUT is defined with a global scope elsewhere in the program (as it may be in the future), we don't want to clobber it, so local within a block is a good idea.

Next, we open that filehandle to write (that's what the angle brace is for) to the filename. If that doesn't work, we print an error message using the special variable $! (which holds the error message from the failed open call).

After that, we print to the filehandle. No big deal there. Finally, we close the filehandle and again print an error message if it fails. That's the end of the block.

This is by far the easiest way to save changes to a file. Other options include using sysread and syswrite or using append mode (">> filename_here"), but if your file is small enough to fit into memory all at once, just do it this way.


In reply to Re: How do I save changes made to a file by chromatic
in thread How do I save changes made to a file by Anonymous Monk

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.