在下面的小代码中,我没有收到行 [09] 和 [18] 的错误或警告。我得到的唯一警告是第 [21] 行:
use strict; # [01]
use warnings FATAL => 'unopened'; # [02]
# [03]
open(my $outHandleA, ">outputA.txt") or die ("A: $!\n"); # [04] Opened $outHandleA
print $outHandleA "FILE A\n"; # [05]
close $outHandleA; # [06] Closed $outHandleA
# [07]
print $outHandleA; # [08]
print $outHandleA "ABC\n"; # [09] <---
print $outHandleA; # [10]
print "-----"; # [11]
# [12]
open(OUT, ">outputB.txt") or die ("B: $!\n"); # [13] Opened OUT
print OUT "FILE B\n"; # …Run Code Online (Sandbox Code Playgroud) 下面的 Perl 程序在执行过程中不输出任何错误。有没有办法在执行时引发异常以尝试打印到未声明的句柄?对于下面的情况,未声明的句柄将是STD_ERRand 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";
Run Code Online (Sandbox Code Playgroud)
虽然上面的代码是为了说明问题而简化的,但我有点浪费了几十分钟试图找出我的实际程序中的问题。在我的实际程序中,我意识到我拼错了要打印的句柄。我想避免这种浪费时间,但use strict;就是不这样做。
执行以下简化代码时:
use strict; # [01]
use warnings FATAL => 'unopened'; # [02]
# [03]
my ($inHandle, $outHandle) = (\*STDIN, \*STDOUT); # [04]
print $outHandle "STDOUT 1\n"; # [05]
# [06]
# $outHandle re-assigned to outputA.txt ??? # [07]
open($outHandle, ">outputA.txt") or die ("A: $!\n"); # [08]
print $outHandle "FILE A\n"; # [09]
print "STDOUT? 2\n"; # [10]
print STDOUT "STDOUT 3\n"; # [11]
close $outHandle; # [12]
# [13]
# $outHandle is closed # [14]
print STDOUT "STDOUT 4\n"; # …Run Code Online (Sandbox Code Playgroud)