| Prev | Perl Notes |
Next |
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:
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.
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 |