1. Technology

How to Read and Write Files in Perl

Writing to a File in Perl


Let's take the same data file we worked with while learning to read a file in Perl, and we'll write to it this time. In order to write to a file in Perl, you must open a filehandle and point it at the file you're writing. If you're using Unix, Linux, or a Mac, you might also need to double check your file permissions to see if your Perl script is allowed to write to the data file.
 open (MYFILE, '>>data.txt');
 print MYFILE "Bob\n";
 close (MYFILE); 
If you run this program, then run the program from the previous example on reading a file in Perl, you'll see that it's added one more name to the list.
In fact, every time you run the program it will add another Bob to the end of the file. This is happening because we opened the file in append mode. To open a file in append more, just prefix the filename with the >> symbol. This tells the open function that you want to write to the file by tacking more onto the end of it. If instead you want to overwrite the existing file with a new one, you can use the > single greater than symbol to tell the open function that you want a fresh file each time. Try replacing the >> with a > and you'll see that your data.txt file is cut down to a single name - Bob - each time you run the program.
 open (MYFILE, '>>data.txt'); 
Next we use the print function to print our new name to the file. You print to a filehandle simply by following the print statement with the filehandle.
 print MYFILE "Bob\n"; 
Finally we close the filehandle to finish out the program.
 close (MYFILE); 
Previous: Reading a file in Perl
Related Video
How to Share Files between your Mac and PC
How to Share Media Files With Windows Media Player
  1. About.com
  2. Technology
  3. Perl
  4. Programming Perl
  5. File System
  6. Writing to a File in Perl

©2014 About.com. All rights reserved.