Prev

Perl Notes

Next

Chapter 8.4 Reading From a File

You can read in one or more lines from external files as necessary.

To read all the data from an external file:

  1. Open the file as described in Chapter 8.1
  2. Type @ARRAY, where ARRAY is the name of the array that will contain each of the lines from the external file.
  3. Type <LABEL>, where LABEL corresponds for the filehandle for the file.
  4. Type ; to complete the line.
  5. Remember to close the file (see Chapter 8.5).

open(FILE, "<../myfile.txt") || &ErrorMessage;
@ARRAY = <FILE>;
close(FILE);

foreach $LINE (@ARRAY) {
  print $LINE; }

sub ErrorMessage {
  print "Could not open file. It either does not exist or the permissions are wrong\n";
  exit;
}

Here's an even simpler method:

open(FILE, "<../myfile.txt") || die "Could not open file $!";
while ($line=<FILE>) {
  print $line;
}
close(FILE);


Prev Home Next