Perl: Appending and Writing to Files - Writing to Files
(Page 2 of 5 )
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
Next: Overwriting Without Deleting Everything >>
More Perl Articles
More By James Payne