The problem is that Perl does not return with non-zero exit status for this condition ( sudo passes the exit status of the command it gave), which is a little annoying. You can solve this problem by learning that the line reading cycle is never entered if the file cannot be renamed and process it using the flag:
sudo perl -i -ne 's/foo/bar/; print; $wrk = 1; }{ $wrk or exit 1' config.txt
The Ekimos greeting (or butterfly) "operator" }{ introduces an END block in a sense; what happens after it is executed when the lines of reading the loop from the file have ended. How this works is described here .
The caveat is that it will also report an error if config.txt empty. In short, if a slightly hacky way is to use the special string counter variable $. for the same purpose:
sudo perl -i -ne 's/foo/bar/; print; }{ $. or exit 1' config.txt
source share