Writing and Appending to Files
Writing and Appending to Files
-
You can do more than just read a file of course. You can also open a filehandle
for writing with the greater than sign (>) using the syntax:
open ([FILE_HANDLE_NAME], ">[filename]");
or for appending using the double-greater-than symbol (>>) with the syntax:
open ([FILE_HANDLE_NAME], ">>[filename]");
The difference between appending and writing is that when you write to
a file, you erase whatever was previously there whereas when you append
to a file, you simply add the new information to the end of whatever text
was already there.
| If the file that Perl
is asked to write or append to does not already exist, Perl will create
the file for you. |
-
Typically, when writing to a file, you use the print function. However,
instead of printing to standard output, you would specify the filename
to print to. Consider the following example:
open (TEMP_FILE, ">temp.file") ||
&CgiDie ("Cannot open temp.file");
print TEMP_FILE "hello there\n";
close (TEMP_FILE);
The file "temp.file" will now have the solitary line:
hello there
Additional Resources:
Reading
a File Line by Line
Table of Contents
Deleting, Renaming
and Changing the Permissions of Files
|