Wednesday, 28 August 2013

How to resolve : print() on closed filehandle in perl

How to resolve : print() on closed filehandle in perl

Error "print() on closed filehandle" generated in the following condition ( it is on of possible cause of it)

-------------------------- BEGIN Code ---------------------------------------
my $inputFile = '/this/is/path/of/your/input/file.txt';
open(MYINPUTFILE, ">","$inputFile");
print MYINPUTFILE "any data";
close(MYINPUTFILE);
-------------------------- END Code ---------------------------------------

here if you don't have permission to access the path '/this/is/path/of/your/input/file.txt' or the path (of parent directory) does not exist then it will throuw the error : print() on closed filehandle

To resolve this better to make practice as follow while opening the file:

-------------------------- BEGIN Code ---------------------------------------
open(MYINPUTFILE, ">","$inputFile") or die "ERROR ::: unable access the file";
-------------------------- END Code ---------------------------------------

So it won't executes the lines after the open file if there is issue in opening file, else it will execute the following lines and gives the error where you tries to access the File.