http://www.perlmonks.org?node_id=1054992

Harkers has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm completely new to PERL so sorry if this is a stupid question. What I want to happen is have text $oldstr replaced with $newstr and a counter (so $newstr text 1, 2, 3 for each instance of replacement) across a batch of files in a particular folder (although I'm only working on one file directly as yet). One of the problems I'm having is the counter is including the lines in between, so my replacement text is $newstr text 3, 9 11 etc. How do I get the counter to only add 1 when the $oldstr is found and replaced by the $newstr? any help much appreciated

use strict; open(FILE, "<test.xml") || die "File not found"; my @lines = <FILE>; close(FILE); my $oldstr = "core:para"; my $newstr = "core:para edpnum\-start\=\""; my @newlines; my $counter =0; foreach(@lines) { if ($oldstr =~ /core\:para/){ $counter = $counter +1; } $_ =~ s/$oldstr/$newstr$counter/g; push(@newlines,$_); } open(FILE, ">test.xml") || die "File not found"; print FILE @newlines; close(FILE);