Reading from and Writing to Files

This web page discusses the following

Opening Files

You must first open a files before you can either read or write to it, basically it lets the Operating System know that no one else can modifiy the file while you have it open. When you open a file you must supply two arguments

The filevar name (also known as a file handle) can be any sequence of letters, digits and underscores, as long as the first character is a letter, also do not use any keywords.

The file can be opened in one of three modes, the success status is return, true means the files sucessfully opened, false means the file was not opened.

read mode open(MYFILE, "file1");
write mode

open(MYFILE, ">file1");

Note: notice the '>' character before the filename, this means write mode

append mode

open(MYFILE, ">>file1");

Note: notice the '>>' character before the filename, this means append mode

Checking if the file was opened

if ( open(MYFILE, ">file1") ) {
    print "SUCCESS: the file was opened sucessfully";
}

Reading from a file

Once the file has been opened you can now read from it, you enclose the file handle in angle brackets (< and >).

Reading from a file if (open(MYFILE, "file1") {         ## Create a Read-Only file handle
   $line = <MYFILE>;                ## Read in a line
   while (line ne "") {
      print ($line);
      $line = <MYFILE>;             ## Read in a line
   }
}
Read the entire contants of a file into an array

open(MYFILE, "file1") || die("ERROR: unable to open file file1\n");
@input = <MYFILE>;
print (@input);

Note: we use the die function to abort if we cannot open the file

Writing to a file

After the file has been opened in write or append mode you can write to the file.

Writing to a file

## Open the file in Read-Only mode
open(DATAFILE, "file1") || die("ERROR: unable to open file file1\n");

## The file contents will be destroyed
open(WRITEFILE, ">file2") || die("ERROR: unable to open file file2\n");

## The contents will not be destroyed, the data will be appended to the file
open(APPENDFILE, ">>file3") || die("ERROR: unable to open file file2\n");

$line = <DATAFILE>;
while ($line ne "") {
   print WRITEFILE ($line);
   print APPENDFILE ($line);
}

Specifying Read and Write Access

To open a file for both readand write access, specify +> before the filename

Read, Write access example

open(DATAFILE, "+>file1") || die("ERROR: unable to open file file1\n");

Note: this options allows you to overwrite portions of a file, it is mainly used with seek and tell which enable you to skip to the middle of a file

 

Standard Ouput and Standard Error

Both the standard output and error point by default to the display but there is no reason why these can point to file.

redirecting STDOUT and STDERR

open(STDERR, ">c:/perl/error.log") || die("ERROR: unable to open error logfile\n");

open(STDOUT, ">c:/perl/program.log") || die("ERROR: unable to open program logfile\n");

Closing Files

Once you are done with a file you should close it, this lets the Operating System know you are done with it, so that others can use your file.

Close a file close(MYFILE);

File-Test Operators

There are a number of file test-operators, to check the status of a file, to see a full listing check the perl cheat sheet.

File-Test operator example one

if ( -e "file1") {
   open(MYFILE, "file1") || die("ERROR: unabl;e to open file file1");
} else {
   print "ERROR: file does not exists";
}

Note: check that the file exists

File-Test operator example two

if ( (-e "file1") && (-w "file1") ) {
   open(MYFILE, "file1") || die("ERROR: unabl;e to open file file1");
} else {
   print "ERROR: file does not exists or is not writeable ";
}

Note: check that the file exists and is writeable

File-Test operator example three

print "File size: " . (-s "c:/perl/error.log") . " bytes";

Note: obtain the size of a file

File-Test operator example four
if ( -e MYFILE ) { ... }      ## you can even use the file handle name,
                              ## but only when the file has been opened

Reading from a Sequence of Files

There are times when you want to read multiple files, in Perl there is a special operator that do read mutliple files in one go the <> operator. The <> operator reads from the first file until it is exhausted, then reads the next file and so on.

<> operator example

## Reading into an variable
while ($data = <>) {         ## when finished a null string will be passed terminating the loop
   print ($data);
}

## Reading into an array
@array = <>;                 ## you can now process the array as you wish

## The commandline would be as follows
perl_program file1 file2 file3

Note: the code above will read all 3 files that were passed as arguments.

Using Commandline Arguments

Perl enables you to use commandline arguments any way you want by defining a special array variable called @argv. When Perl starts this variable contains a list consisting of the commandline-arguments..

Commandline-argument example

## Perl command to run
perl_prog hello world

## The array @argv will contain the arguments passed
print("@argv");

## Access each argument individually
print ("First argument passed: $argv[0]");
print ("Second argument passed: $argv[1]");
print ("Third argument passed: $argv[2]");

The special operator <> uses the @argv array to get the file names if passed.