将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抛出错误而不仅仅是警告?
答案 0 :(得分:1)
使用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
$