Prev

Perl Notes

Next

Chapter 8.1 Opening a File

Before you can read or write to a file, you have to open a connection to it and assign it a label or filehandle.

To open a file:

  1. Type open(.
  2. Type LABEL,, where LABEL is the filehandle. You'll use this label from this point on when referring to the file. Don't forget the comma.
  3. Type ".
  4. If you want to be able to write to the file, type >. Any existing contents in the file will be lost.

    Or, to append data to the file, type >>. Existing data is left unchanged with new data following directly thereafter (with no spaces or spaces or returns seperating them).

    Or, to simply read or input data from the file, no extra symbol is required. (If you like being explicit, type <.)
    For more options see operation modes.

  5. Type filename, (directly after the symbol in step 4, if any) where filename is the actual name, including the path if necessary, of the file you wish to open. You can also use a scalar variable or expression for the filename.
  6. Type ".
  7. Type ) to complete the function.
  8. Type ; to complete the line.
open(FILE, ">>../myfile.txt");
print FILE "I'm adding text to a file.\n";
close(FILE);

Unfortunately, Perl will continue running a script even if it hasn't been able to open the external file. Therefore, it's a good idea to create a manual alert system in case something goes wrong. You can create a subroutine that prints out an error message and then exits the script.

open(FILE, ">>../myfile.txt") || &ErrorMessage; print FILE "I'm adding text to a file.\n"; close(FILE); sub ErrorMessage { print "Could not open file. It either does not exist or the permissions are wrong\n"; exit; }

Or you can have it simply die. In this case while reading form a file:

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