Before I answer your question, let's address two things.
First of all, you have a useless use of backticks. Use system instead.
for my $file (@files) {
system("sudo perl ...");
}
Second of all, you are not properly converting the contents of $file into a shell literal. Consider what would happen if $file contains a single-quote. Fix:
use String::ShellQuote qw( shell_quote );
for my $file (@files) {
system(shell_quote('sudo', 'perl', ..., $file));
}
or you can avoid the shell entirely:
for my $file (@files) {
system('sudo', 'perl', ..., $file);
}
On to your question.
-p causes Perl to wrap the program with
while (<>) {
... -e ...
} continue {
print;
}
As such,
/foo(\r\nfoo2)/
or the more flexible
/foo(\s*\nfoo2)/
can't possibly match since you haven't read foo2 yet. You could cause <> to read the entire file by executing local $/; first, which can be done by adding -0777 to get
$/ = undef;
while (<>) {
...[ code from -e ]...
} continue {
print;
}
So what you need is:
for my $file (@files) {
system('sudo', 'perl', '-i', '-0777pe', 's/foo(\s*\nfoo2)/bar$1/', $file);
}
Or you could even avoid the for loop and use
system('sudo', 'perl', '-i', '-0777pe', 's/foo(\s*\nfoo2)/bar$1/', @files);