Alex Rivera | Logout

How do I resolve a "print() on closed filehandle" error in Perl?

Asked 2009-05-30T11:36:38.257
13

I am getting this error while executing my Perl script. Please, tell me how to rectify this error in Perl.

print() on closed filehandle MYFILE

This is the code that is giving the error:

sub return_error
{
    $DATA= "Sorry this page is corrently being updated...<p>";
    $DATA.=  "<A href=\"javascript:history.go(-1)\"> Back </A>";
    open(MYFILE,">/home/abc/xrt/sdf/news/top.html");
    print MYFILE $DATA;
    close(MYFILE);
    exit;
}

I hope that now I'm clearer.

Edit
Report

2 Answers

3

This:

open(MYFILE,">/home/abc/xrt/sdf/news/top.html");

In modern Perl, it could be written as:

open(my $file_fh, ">", "/home/abc/xrt/sdf/news/top.html") or die($!);

This way you get a $variable restricted to the scope, there is no "funky business" if you have weird filenames (e.g. starting with ">") and error handling (you can replace die with warn or with error handling code).

Once you close $file_fh or simply go out of scope, you can not longer print to it.

answered 2009-05-30T12:38:31.500
2

If you use a global symbol MYFILE as your filehandle, rather than a local lexical ($myfile), you will invariably run into issues if your program is multithreaded, e.g. if it is running via mod_perl. One process could be closing the filehandle while another process is attempting to write to it. Using $myfile will avoid this issue as each instance will have its own local copy, but you will still run into issues where one process could overwrite the data that another is writing. Use flock() to lock the file while writing to it.

answered 2009-06-01T18:19:34.133

Your Answer