Perl: Appending and Writing to Files (Page 1 of 5 )
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.
How to Append to a File
Sometimes you want to append or add additional information to a file. To do so is simple. Just open up the file with the original data and add however many lines you wish to the end of the page. Let's say we want to some data to our superhero.txt file.
Here is what it originally looked like:
The Incredible Hulk|Super Strength|I rip my pants
Daredevil|Heightened Senses|I have poor fashion sense due to blindness
Apache Chief|the ability to grow Very Tall|I wear a skirt
Now are going to add a new row for the superhero I consider to probably be the lamest of all:
Aqua Man|the ability to communicate with fish|deep fryers and tartar sauce
Our superhero.txt file should now look like this:
The Incredible Hulk|Super Strength|I rip my pants
Daredevil|Heightened Senses|I have poor fashion sense do to blindness
Apache Chief|the ability to grow Very Tall|I Wear a skirt
Aqua Man|the ability to communicate with fish|deep fryers and tartar sauce
Amazing right?
Of course we can also append data with code, like so:
$my_file="suphero.txt";
open(PLOT,">>$my_file") || die("This file will not open!");
print PLOT "Aqua Man/|the ability to communicate with fish/|deep fryers and tartar saucen";
close(PLOT);
I know that the above code looks a little convoluted. You will notice several differences right off the bat. First, when we open the file we use double quotes after the comma, and we have added two greater than characters (>>) to the front of the filename we wish to open. These two greater than symbols tell the program we wish to append data and not read or overwrite data.
Next we use our buddy the print command, followed by our referencer PLOT, to place the data in our table. As you can see, we use the pipe(|) delimiter again to separate the columns. Before we place the pipes(|) in however, we must first escape using the backslash(/). Finally, we add an n (newline) to the end of the sentence and close our connection.
We could accomplish the same thing using variables:
$my_file="superhero.txt";
$heroname="Aqua Man";
$heropower="the ability to communicate with fish";
$heroweakness="deep fryers and tartar sauce";
open(PLOT,">>$my_file") || die("The file cannot be opened!");
print DAT "$heroname|$heropower|$heroweaknessn";
close(PLOT);
This will have the same affect as our previous code, although it may be a little easier to read and understand.
Next: Writing to Files >>
More Perl Articles
More By James Payne