Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need perl to die when implicit open fails

Tags:

linux

perl

I'm trying to migrate a sed script to a perl one-liner, because perl supports non-greedy regexp. I've taken advices from Non greedy (reluctant) regex matching in sed? and Why is my Perl in-place script exiting with a zero exit code even though it's failing?

I need my oneliner to exit with non-zero status if it failed to open the file.

Unfortunately, checking -f $ARGV[0] is unreliable, because the file may exist and still be inaccessible.

One idea is to add some perl code to execute between all files in command line, but I can't find one. END is executed once and if the last file succeeded, then it won't know that previous files failed.

touch aaa.txt
chmod 000 aaa.txt
perl -i -pe 'BEGIN { -f $ARGV[0] or die "fatal: " . $!; }' aaa.txt; echo $?

_

Can't open aaa.txt: Permission denied.
0
like image 656
basin Avatar asked Oct 18 '19 13:10

basin


People also ask

Why can't I use fatal on a perl built-in?

You've tried to use Fatal on a Perl built-in that can't be overridden, such as print or system, which means that Fatal can't help you, although some other modules might. See the "SEE ALSO" section of this documentation.

What is Runrun time error in Perl?

Run Time Error : It is an error that occurs when the program is running and these errors are usually logical errors that produce the incorrect output. Perl provides two builtin functions to generate fatal exceptions and warnings, that are:

What is error handling in Perl?

Error Handling in Perl is the process of taking appropriate action against a program that causes difficulty in execution because of some error in the code or the compiler. Processes are prone to errors.

How to identify and trap errors in Perl?

You can identify and trap an error in a number of different ways. Its very easy to trap errors in Perl and then handling them properly. Here are few methods which can be used. The if statement is the obvious choice when you need to check the return value from a statement; for example −


1 Answers

The Can't open ... text is a warning. You can trap that using the $SIG{__WARN__} signal handler.

As the only warnings you should be getting are from the implicit <> operator in the loop supplied by the -p switch you can rewrite your code like this

perl -i -pe 'BEGIN { $exit = 0; $SIG{__WARN__} = sub { $exit = 1; warn @_} } END { $? = $exit}' aaa.txt; echo $?

This sets $exit to 0 at the start of the script and sets it to 1 if there is a warning. The END block assigns the value of $exit to $? which will be the exit code of the script once it ends.

like image 82
JGNI Avatar answered Sep 20 '22 05:09

JGNI