Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: find and replace counter

by msbalaji (Chaplain)
on Jan 08, 2008 at 06:38 UTC ( [id://661014]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://661014]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2025-11-15 00:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (71 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.