I'm not a Perl guru either, but you are evaluating only the first argument and killing your script immediately after the file isn't existent ... This will neither evaluate all files passed as arguments nor continue to process other files if the first argument is a nonexistent file.
Therefor, your script is not going to work as you expect when you pass multiple arguments(filenames) to it.
You need to first evaluate all the command-line arguments with e.g. foreach my $arg (@ARGV) { ... }
then set the exit code accordingly and exit with that code at the end.
i.e. something like this:
perl -p -e 'my $exit_code; BEGIN{
foreach my $arg (@ARGV) {-f $arg or $exit_code = 2} }
END{exit($exit_code)}
s/foo/bar/' non-existent-file.txt existent-file.txt
Notice(might save your time): AFAIK die
doesn’t have an exit status of its own nor does it "directly" alter the script's exit status … Therefor, the exit code number 2
you see is actually for -f $ARGV[0]
and it means no such file or directory
… Those code numbers are limited in variety and are distinct … Therefore, it is perfectly fine to assign/set them manually in a controlled environment as such although if an argument passed might be a directory, then it might result in a different error number but that’s what "controlled" is about as you can change -f
to -e
for instance or double evaluate with a conditional or even add your own extended error evaluation/containment code to do exactly what you want.
Furthermore, die
can have a side effect(exception) that will result in additional error codes e.g. 22
(invalid argument) thus contaminating your script and that might not be what you want if you aim to preserve some actual exit status ... See why here ... You might however be able to contain/neutralize this side effect partially(although might not be reliable ... Use exit
instead) with something like eval{die "blabla" ... }
and in which case this might directly alter your script's exit status as well.
However, you might be able to both use die
and not exit
and preserve the actual exit status from -f $ARGV...
at the same time while not killing your script immaturely if you properly move the evaluation to an END
block with something like this:
perl -p -e 'my @arr; BEGIN{@arr = @ARGV}
END{ foreach my $arg (@arr) { -f $arg or die"no file"} }
s/foo/bar/' non-existent-file.txt existent-file.txt