Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

$ perl -pe 1 foo && echo ok
Can't open foo: No such file or directory.
ok

I'd really like the perl script to fail when the file does not exist. What's the "proper" way to make -p or -n fail when the input file does not exist?

like image 279
William Pursell Avatar asked Dec 06 '19 17:12

William Pursell


2 Answers

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
like image 148
Grinnz Avatar answered Nov 08 '22 03:11

Grinnz


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}'
like image 45
choroba Avatar answered Nov 08 '22 03:11

choroba