in reply to find and replace counter

hi try this

use strict; my $cnt=0; while(<DATA>){ $_ =~s/<xxx>/++$cnt.$&/gie; print $_; } __DATA__ <xxx>...</xxx> <p>...</p> <xxx>...</xxx><xxx>...</xxx> <p>...</p>

Regards
Balaji. M

Replies are listed 'Best First'.
Re^2: find and replace counter
by hipowls (Curate) on Jan 08, 2008 at 07:20 UTC

    Global substitution along with 'e' to evaluate the replacement text is the trick although you'd be better off not using $& as it imposes a cost on all regular expessions in the program. See Special variables. And you left out the '<' and '>'.

    Given that <xxx> is a constant string it isn't worth while capturing it. If the tag is to be passed in a function then something like

    my $html = get('http://use.perl.org'); my $tag = '<xxx>'; # or '<' . shift . '>' or ... my $count = 0; $html =~ s/$tag/ '<' . ++$count . ">$tag" /ge;

    The reference to LWP::Simple was inspired by this blog on Beautiful Code

Re^2: find and replace counter
by texuser74 (Monk) on Jan 08, 2008 at 07:11 UTC
    Thanks Balaji, that solves my problem