# It's good practice to make sure your open succeeds open(FILE,$template) or die "Can't read template: $!"; # while instead of foreach, since while (since it's # scalar context) reads the FILE a line at a time, instead # of slurping it all into memory while () { # replace only your match with the return value of the sub s/MY_MATCH/&do_something/eg; print; } close FILE;