$ 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?
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}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With