我遇到了一个我似乎无法解决的问题,我希望你们能帮助我。
问题发生在:
- 我使用自定义错误处理
- 我在单独的模块中使用 File::Stat
例子:
主文件
use strict;
use warnings;
# signal handling
$SIG{__DIE__} = sub {
my $error = @_;
chomp $error;
print "die: $error\n";
};
require mod;
mod->get_stat();
模块
package mod;
use strict;
use warnings;
use File::stat;
sub get_stat {
my $file_path = "test.txt";
my $file_size = stat($file_path)->size;
print $file_size;
}
1;
这将导致以下输出:
die: 1
die: 1
die: 1
die: 1
die: 1
4
现在,如果我删除我的自定义错误处理,或者如果我使用 mod 而不是require,则不会显示骰子。
有趣的是,它确实实际产生了一个结果(test.txt 是 4 个字节),这意味着 stat 正在正常工作。
那么,为什么我会收到此错误?这真的是一个错误吗?默认的 perl 错误处理是否忽略为“1”的错误?
编辑
正如 Linus Kleen 所说,我得到“1”的原因是因为我显示的是数组中元素的数量。
如果我改为打印出错误的内容,则会收到以下错误:
die: Your vendor has not defined Fcntl macro S_ISVTX, used at c:/Perl64/lib/File/stat.pm line 37.
die: Your vendor has not defined Fcntl macro S_IFSOCK, used at c:/Perl64/lib/File/stat.pm line 41.
die: Your vendor has not defined Fcntl macro S_IFBLK, used at c:/Perl64/lib/File/stat.pm line 41.
die: S_IFFIFO is not a valid Fcntl macro at c:/Perl64/lib/File/stat.pm line 41.
die: Your vendor has not defined Fcntl macro S_IFLNK, used at c:/Perl64/lib/File/stat.pm line 41.
4
但是,我仍然收到一个错误,如果没有自定义错误处理,我不会收到。
最佳答案
如 perlvar 中所述,由于实现故障 $SIG{__DIE__}
Hook 即使在代码 die 时也会被调用在 eval 里面.当File::stat加载后,它会检查常量 Fcntl在您的平台上支持。它会捕获由不受支持的常量引起的错误,但不会在您的钩子(Hook)发现它们之前捕获它们。
您可以通过检查 $^S
的值来判断您是否在 eval
中.如果它不为 0,则说明您处于评估状态。
$SIG{__DIE__} = sub {
return unless defined $^S and $^S == 0; # Ignore errors in eval
my ($error) = @_;
chomp $error;
print "die: $error\n";
};
当您使用 use
而不是 require
时,您看不到错误,因为 use
是编译时操作,而 require
是一个运行时操作(就像设置 %SIG
一样)。当您使用 mod
并且它使用
的 File::stat 时,这一切都发生在您设置钩子(Hook)之前。当您需要 mod
时,它不会发生,直到您已经安装了您的钩子(Hook)。
关于perl - 自定义错误处理正在捕获通常不显示的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8078220/