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. |