Since perl is a programming language, it has I/O manipulation. We will
now look at how this is applied to Files. A filehandle is the name in a
perl program that connects I/O between your perl program and external programs.
Perl has three default file handles which are automatically opened. STDIN (standard input), STDOUT (standard output), and STDERR (for standard error). Filehandles have their own namespace and do not conflict with perl variables. The recommendation fro Larry Wall in declaring filehandles is to use a name that is all uppercase.
In order to open a filehandle you would use the open function:
open(FILEHANDLE,"filename");
FILEHANDLE is the name of our handle and "filename" is the name of the file that we wish to open, true will be returned if it was successful and false if it was not.
To open a file for reading you may use either of the following two syntaxes:
open(FILEHANDLE,"filename");
or
open(FILEHANDLE,"<filename");
If you wish to create a file you would use the following syntax:
open(FILEHANDLE,">filename");
In order to append to an existing file you do the following:
open(FILEHANDLE,">>filename");
Reading from a filehandle is pretty much the same as reading from STDIN:
open(FILEHANDLE,"test.txt");
while(<FILEHANDLE>){
print "line: $_\n";
}
or
@entire_file = <FILEHANDLE>; #this will read in the entire file into the array
or
$one_line = <FILEHANDLE>; #this will read one line into the scalar variable.
In order to write to a filehandle which has been opened for writing you would:
print FILEHANDLE "This line will go into our output file";
If you need to open a file in binary mode then you would use the open function in the same manner as before except that this time you would use one additional function:
open(FILEHANDLE,"filename");
binmode(FILEHANDLE);
The binmode() function forces binary mode treatment of the given file handle on systems that distinguish between text and binary files.
Once we are done using a file handle we should close it:
close(FILEHANDLE);
If you reopen a filehandle before it has been closed it will close the previous file automatically, the same will happen when you exit the program.
There are also some file test that you can run on a specified file handle or file name. Below are a few:
File Test | Meaning |
-r | File or directory is readable |
-w | File or directory is writable |
-x | File or directory is executable |
-o | File or directory is owned by user |
-e | File or directory exists |
-z | File or directory exist and has zero size |
-f | Entry is a plain file |
-d | Entry is a directory |
-T | File is "Text" |
-B | File is "Binary" |
An example of using one of these test would be:
open(FILEHANDLE,"text.txt");
if(-e FILEHANDLE){
print "File exist";
}
or
$filename = "/users/abc123/text.txt";
if(-e $filename){
print "File exist\n";
}
We can perform these file test on either the file handle or the file that we want.
![]() |
![]() |
![]() |