Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: How to process multiple input files?

by John M. Dlugosz (Monsignor)
on May 23, 2011 at 00:42 UTC ( [id://906220] : note . print w/replies, xml ) Need Help??

in reply to How to process multiple input files?

Oh, also your technique to find the second occurrence of something and do something to it is a bit strange. You could use the search /g in a loop and have normal code rather than the inside of evaluated replacement. But, you can locate the second occurrence directly and not need that kind of code.

You want to insert something just before the second </div>, right? Something like this (untested!):

my $replacement= '\t<?php include(\$_SERVER['DOCUMENT_ROOT'].\"\/inclu +des\/footer.php\"); ?>\n\n'; s{ </div> .*? \K (?=</div>) } { $replacement } x;
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.

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:

#!/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; }
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.