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.
code:
#!/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.
code:
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.
code:
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.
code:
chomp; print "$_\n";
Finally we close the filehandle to finish out the program.