How to make perl throw an error for invalid or nonexistent files?

420 Views Asked by At

Using perl with the -p or -n flags or with the diamond operator on non-existent files will not exit with an error:

$ 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.
$

How can I force perl to throw an error, not just a warning, when given a bad file?

1

There are 1 best solutions below

0
On

Use local $SIG{__WARN__} = sub { die @_ }; to set the warning handler to throw an error.

$ # 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
$