1. Computing

How to Read and Write Files in Perl

Reading a File in Perl

By

Next: Writing to a file in Perl

Perl is an ideal language for working with files. It has the basic capability of any shell script, and some very advanced tools, like regular expressions, that make it infinitely more useful. In order to work with files, we first need to learn how to read and write to them. Reading a file is done in Perl by opening a filehandle to a specific resource - in this case a file on our system.

 #!/usr/local/bin/perl
 open (MYFILE, 'data.txt');
 while (<MYFILE>) {
 	chomp;
 	print "$_\n";
 }
 close (MYFILE); 
In order to work with this example, you'll need a file for our Perl script to read. Create a new text document called data.txt and place it in the same directory as the above Perl program. In the file itself, just type in a few names - one per line:
 Larry
 Curly
 Moe 
When you run the script, the output should be the same as the file itself. The script is simply opening the specified file, and looping through it line by line, printing each line as it goes. First we create a filehandle called MYFILE, open it, and point it at our data.txt file.
 open (MYFILE, 'data.txt'); 
Then we use a simple while loop to automatically read each line of the data file one at a time - this places the value of each line in the temporary variable $_ for one loop.
 while (<MYFILE>) { 
Inside the loop, we use the chomp function to clear off the newlines from the end of each line, then we print the value of $_ to show that it was read.
 	chomp;
 	print "$_\n"; 
Finally we close the filehandle to finish out the program.
 close (MYFILE); 
Next: Writing to 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. Computing
  3. Perl
  4. Programming Perl
  5. File System
  6. How to Read and Write Files in Perl - Tutorial on Reading and Writing Files in Perl

©2014 About.com. All rights reserved.