File Processing

Opening and Reading Files

In this lesson the student will learn to:
  1. Open and read files using Perl commands.
  2. Use the open command.
  3. Use the <FILE> construct.
  4. Process the contents of a file.
By the end of this lesson the student will be able to:

   Write a short Perl script which opens a file
   and displays the contents of the file.



OPENING AND READING FROM FILES:

If you're going to work with the content of a file, then you need to be able to open the file and access the information stored in that file. The following example shows you how to access the information in the file one line at a time:

#!/usr/bin/perl -w open (FILE, "gern.xml"); $line1 = <FILE>; print $line1; $line2 = <FILE>; print $line2; $line3 = <FILE>; print $line3; close(FILE); exit;
Closing a file is optional. Actually, the FILE variable in this example is referred to as a filehandle and so it would be more proper to say that closing a filehandle is optional. A filehandle is automatically closed at the end of a program.
OPENING AND READING FULL FILE:

Here's a Perl script that opens a file and then reads it one line at a time until there are no more lines left to read:

#!/usr/bin/perl -w if(open (FILE, "dvsa.xml")){; $line = <FILE>; while($line){ print $line; $line = <FILE>; } } else{ print "NO FILE OPENED\n"; } exit;


DEALING WITH FILES THAT WON'T OPEN:

Things don't always go according to plan. Sometimes files don't open as expected for any number of reasons. You should deal with this possibility when writing your script:

#METHOD ONE: if(open(FILE, "file.txt")){ # do stuff } else{ die ("File open failed\n"); } #METHOD TWO: unless(open(FILE, "file.txt")){ die ("File open failed\n"); } # do stuff #METHOD THREE: open(FILE, "file.txt") || die ("File open failed\n");



READING FILE CONTENTS USING AN ARRAY:

It is convenient to use an array when reading a file:

#!/usr/bin/perl -w open (FILE, "gern.xml") || die; @ray = <FILE>; foreach $line (@ray){ print $line; } exit;
EXAMPLE FILES:
gern.xml
dvsa.xml



ASSIGNMENT:
Write the following two scripts:
  1. Script One: Opens a file and prints the entire contents of the file backwards. (Look up how to use the reverse function on arrays.)
  2. Script Two: Opens a file and allows the user to press the space bar to display one line of the file at a time until the end of the file is reached or the user presses the 'q' key.