In our last tutorial we left off on the topic of creating files and manipulating the data therein. In this article we will discuss how to append to a file and how to write to a file. If there is time, we will also discuss working with file checks.
The phrase "writing to files" is a little misleading. When I think of writing to a file, I am really thinking of appending to the file. Why they didn't just name it Overwriting Files, I will never know, because that is really what you are doing. Basically the original file is overwritten and new data is written in its place.
Let's say we want to get rid of all the heroes in our database and add news ones to it. We do it the same way we append to a file except for this line:
open(DAT,">$my_file") || die ("The file has died!");
As you can see, we now only use one greater than (>) key. This tells the program that we are writing (or overwriting) data. You assign the new values the same way as before.
$my_file="superhero.txt";
$heroname="Batman";
$heropower="None. He does not need them";
$heroweakness="Slow speech and Action Bubbles";
open(PLOT,">$my_file") || die("The File is dead!");
print PLOT "$heroname|$heropower|$heroweaknessn";
close(PLOT);
If we printed this file, this would be the contents: Batman|None. He does not need them|Slow speech and Action Bubbles