Files I/O

Filehandle is used to open or close a file in Perl.

How to Open a file?

open(filehandle,mode,filename)
  • filehandle is a variable which associates with the file
  • Below are the modes available in Perl
ModeSymbol
read<
write>
append>>
  • Filename is the name of the file you want to open along with filepath.

Example

Consider you want to read sample.txt file:

open(FH, '<', 'c:\sample.txt');

How to close a file?

You must close the file after finishing read or write operations on the file. close() function is used to close a file.

close(FH);

File test Operators

Below are some of the frequently used test operators which helps in checking about the file before performing read or write operations:

File test OperatorDescription
-rchecks if the file is readable
-wchecks if the file is writable
-xchecks if the file is executable
-ochecks if the file is owned by effective uid.
-Tchecks if the file is an ASCII text file.
-Bchecks if the file is a binary file.
-echecks if the file exists.
-zchecks if the file is empty.
-schecks if the file has nonzero size.
-fchecks if the file is a plain file.
-dchecks if the file is a directory.
-lchecks if the file is a symbolic link.
-pchecks if the file is a named pipe (FIFO.
-Schecks if the file is a socket.
-bchecks if the file is a block special file.
-cchecks if the file is a character special file.

Example

my $filename = 'c:\sample.txt';
if(-e $filename && -r _){
   print("$filename is present and readable \n");
}else{
   print("$filename is neither present nor readable\n");
}