Entry
How do I write to a file?
Jul 19th, 2001 21:56
Phil S., Per M Knutsen,
You must open the file you want to write to and create a filehandle.
Example:
# open file for writing
open(OUT, "&lgt;test.txt") || die("Error: unable to open file\n");
# print 'Hello Perl World' to "test.txt" via its handle
print(OUT "Hello Perl World!\n");
# Close file when finished
close(OUT);
You can also add to an existing file by using >> instead of > (or
&lgt;).
Example:
# open file for writing
open(FILE,">>test.txt") || die("Error: unable to open file\n");
# now print 'Hello Again!' to the next line "test.txt"
print FILE "Hello Again!\n";
# Close file when finished
close(FILE);