将Perl与-p或-n标志一起使用,或对不存在的文件使用菱形运算符将不会退出并出现错误:

$ perl -pe '' badfile || echo error
Can't open badfile: No such file or directory.
$
$ perl -ne '' badfile || echo error
Can't open badfile: No such file or directory.
$
$  perl -e 'print while <>' badfile || echo error
Can't open badfile: No such file or directory at -e line 1.
$

当给定错误文件时,如何强制perl引发错误,而不仅仅是警告?

最佳答案

使用local $SIG{__WARN__} = sub { die @_ };设置警告处理程序以引发错误。

$ # Put handler code in BEGIN block for -p and -n:
$ perl -pe 'BEGIN{$SIG{__WARN__}=sub{die @_}}' badfile || echo error
Can't open badfile: No such file or directory.
error
$
$ perl -ne 'BEGIN{$SIG{__WARN__}=sub{die @_}}' badfile || echo error
Can't open badfile: No such file or directory.
error
$
$ perl -e '$SIG{__WARN__}=sub{die @_}; print while <>;' badfile || echo error
Can't open badfile: No such file or directory at -e line 1.
error
$

07-24 09:47