-1

在不存在的文件上使用带有 -p 或 -n 标志或菱形运算符的 perl 不会因错误而退出:

$ 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 抛出错误,而不仅仅是警告?

4

1 回答 1

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
$ 
于 2015-06-03T00:38:35.363 回答