in reply to How to process multiple input files?
You want to insert something just before the second </div>, right? Something like this (untested!):
Note that you don't use /g so don't keep checking all the rest of the divs, and you don't use $1 or anything in the replacement but "insert" it without replacing any of the stuff used to find that spot.my $replacement= '\t<?php include(\$_SERVER['DOCUMENT_ROOT'].\"\/inclu +des\/footer.php\"); ?>\n\n'; s{ </div> .*? \K (?=</div>) } { $replacement } x;
The \K means that what came before is just context and not included in what gets replaced. The (?=pattern) does the same for what follows. Nothing is "in" the region replaced. See also the use of lazy quantifiers.
The whole program becomes:
I added comments and changed the name of the variable from $line because nobody else noticed that this is not a single line. As written, it was confusing and hard to read because of built-in assumptions people make about idioms and style.#!/usr/bin/perl use strict; use warnings; $^I = ".bak"; # same as -i option undef $/; # slurp whole files! my $replacement= '\t<?php include(\$_SERVER['DOCUMENT_ROOT'].\"\/inclu +des\/footer.php\"); ?>\n\n'; my $filecontents; while (defined ($filecontents=<>)) { $filecontents =~ s { </div> .*? \K (?=</div>) } { $replacement } x; print $filecontents; }
|
|---|