Filehandles

You can create your own filehandles using the open function, read and/or write to them, and then clean up using close.

open

open opens a file for reading and/or writing, and associates a filehandle with it. You can choose any name for the filehandle, but the convention is to make it all caps. In the examples, we use FILEHANDLE.

open a file for reading
open FILEHANDLE,"cosmids.fasta"
alternative form:
open FILEHANDLE,"<cosmids.fasta"

open a file for writing
open FILEHANDLE,">cosmids.fasta"

open a file for appending
open FILEHANDLE,">>cosmids.fasta'

open a file for reading and writing
open FILEHANDLE,"+<cosmids.fasta"

Catching Open Failures

It's common for open to fail. Maybe the file doesn't exist, or you don't have permissions to read or create it. Always check open's return value, which is TRUE if the operation succeeded, FALSE otherwise:

$result = open COSMIDS,"cosmids.fasta";
die "Can't open cosmids file: $!\n" unless $result;

When an error occurs, the $! variable holds a descriptive string containing a description of the error, such as "file not found".

There is a compact idiom for accomplishing this in one step:

open COSMIDS,"cosmids.fasta" or die "Can't open cosmids file: $!\n";

Using a Filehandle

Once you've created a filehandle, you can read from it or write to it, just as if it were STDIN or STDOUT. This code reads from file "text.in" and copies lines to "text.out":


 open IN,"text.in"    or die "Can't open input file: $!\n";
 open OUT,">text.out" or die "Can't open output file: $!\n";

 while ($line = <IN>) {
   print OUT $line;
 }

Closing a Filehandle

When you are done with a filehandle, you should close it. This will also happen automatically when your program ends, or if you reuse the same filehandle name.

close IN or warn "Errors while closing filehandle: $!";

Some errors, like filesystem full, only occur when you close the filehandle, so you should check for errors in the same way you do when you open a filehandle.


<< Previous
Contents >> Next >>

Lincoln D. Stein, lstein@cshl.org
Cold Spring Harbor Laboratory
Last modified: Thu Oct 12 22:21:54 EDT 2000