If you could provide a Short, Self-Contained, Correct Example that includes sample input and the expected output for that input, we would be able to help better. I also don't understand your comments like "Need to get count back to main", perhaps because of some missing context? In regards to your logic, IMHO you're running the regex too often; in particular, you're incrementing $Count if you find the pattern in the line, after having run the s///g, which means that unless $replacement happens to match $pattern, the regex won't match and you won't increment $Count!
You only need to run the regex once, and you can use the regex's return value in the single if statement you need for this code. Another thing to note is that you don't necessarily need to first read the file into memory (@lines), as this will be inefficient for large files; the typical solution is writing to a temporary file while still reading from the input. This is what Perl's -i switch does (which can be done via $^I), and what my module File::Replace does while trying to be more robust (more error checking instead of warnings, and atomic file replacement if supported by the OS and filesystem). That's why I'm using the latter in the following code, but you could continue using your read-to-memory version if your input files will always be small enough to fit into memory. The important thing here is the loop body.
use warnings;
use strict;
use feature 'say';
use File::Replace 'replace3';
my ($file, $pat, $replace) = @ARGV;
my $Count = 0;
my ($infh, $outfh, $rep) = replace3($file);
while (<$infh>) {
chomp;
if ( s/$pat/$replace/g )
{ $Count++ }
say {$outfh} $_;
}
$rep->finish;
say "Count=$Count";
Of course, if this is all your program is doing, you can do it with a oneliner too, e.g.:
perl -wMstrict -i -nle 's/PAT/REPL/g and $a++;print}{print $a//0' FILE
Update: If you need to account for multiple replacements in the line, you can replace the whole if in the above script with $Count += s/$pat/$replace/g;, as s///g returns the number of replacements made. In the oneliner that'd be '$a+=s/PAT/REPL/g;print}{print$a//0' (BTW, see "Eskimo greeting" in perlsecret in regards to the trick used in the oneliner). |