my $bpt_counter=0; my $ept_counter=0; for ($YOUR_ENTIRE_TEXT_IN_ONE_STRING) { s/(<p>)/++$bpt_counter;qq($1)/eg; s|(</p>)|++$ept_counter;qq($1)|eg; } #just to be safe warn "Uh-oh!\n" unless $bpt_counter == $ept_counter;