open(FILE, $file) or die $!; @lines = ; close FILE; for ($i = 0; $i <= $#lines; $i++) { if ($lines[$i] =~ /<% INCLUDE file(\d+)\.txt %>/) { $num = $1; # UPDATE: # ok, the next line (original) is wrong, see replies # $num = $num == 1 ? 1 : 2; # We have to write it this way: $num = $num == 1 ? 2 : 1; $lines[$i] =~ s/<% INCLUDE file(\d+)\.txt %>/<% INCLUDE file$num\.txt %>/; } else { next; } open(FILE, ">$file") or die $!; print FILE @lines; close FILE;