Catching undeclared use of a filehandle in Perl

Viewed 69

The following Perl program does not output any error during execution. Is there a way to raise an exception while execution for trying to print to an undeclared handle? For the case below, the undeclared handle will be STD_ERR and DOES_NOT_EXIST.

use strict;

print STD_ERR        "(UNDECLARED) DOES NOT PRINT\n";
print STDERR         "     (EXIST) DOES PRINT\n";
print DOES_NOT_EXIST "(UNDECLARED) DOES NOT PRINT\n";

Although the above code is simplified to illustrate the problem, I kind of wasted couple of tens of minutes trying to figure out the issue in my real program. In my real program, I realized that I misspelled the handle I want to print against. I want to avoid this kind of waste of time, but use strict; simply doesn't do it.

1 Answers

You can use use warnings 'unopened' to warn about usage of unopened file handles. To make the warning fatal (i.e. throw an exception) you can use:

use warnings FATAL => 'unopened';

See also perldoc warnings and perldiag

Related