Writing

To write data to a file, you must first have a filehandle open for writing. The syntax for opening a file for writing is almost identical to reading:

open( filehandle, ">pathname")
open( filehandle, ">>pathname")

The first syntax line should look familiar, except for the > in front of the pathname. The > signifies to Perl that the file specified at pathname should be overwritten with new data, that any existing data should be discarded, and that filehandle is open for writing. In the second example, >> tells Perl to open the file for writing but, if the file exists, to append data to the end of it. Now check out these examples:

 # Overwrite existing data, if any open(NEWFH, ">output.txt") || die "Opening output.txt: $!"; # Simply append ...

Get Sams Teach Yourself Perl in 24 Hours now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.