How best (idiomatically) to fail perl script (run with -n/-p) when input file not found?

The -p switch is just a shortcut for wrapping your code (the argument following -e) in this loop:

LINE:
  while (<>) {
      ...             # your program goes here
  } continue {
      print or die "-p destination: $!\n";
  }

(-n is the same but without the continue block.)

The <> empty operator is equivalent to readline *ARGV, and that opens each argument in succession as a file to read from. There's no way to influence the error handling of that implicit open, but you can make the warning it emits fatal (note, this will also affect several warnings related to the -i switch):

perl -Mwarnings=FATAL,inplace -pe 1 foo && echo ok

Set a flag in the body of the loop, check the flag in the END block at the end of the oneliner.

perl -pe '$found = 1; ... ;END {die "No file found" unless $found}' -- file1 file2

Note that it only fails when no file was processed.

To report the problem when not all files have been found, you can use something like

perl -pe 'BEGIN{ $files = @ARGV} $found++ if eof; ... ;END {die "Some files not found" unless $files == $found}'

Tags:

Perl