faqts : Computers : Programming : Languages : Perl : Common Problems : File Handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

27 of 33 people (82%) answered Yes
Recently 7 of 10 people (70%) answered Yes

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);