简体   繁体   中英

Catching undeclared use of a filehandle in Perl

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.

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

use warnings FATAL => 'unopened';

See also perldoc warnings and perldiag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM