loop over a string to do search/replacement using regexp?

R

Rick

Hi, guys

I need to loop over a string to find some pattern A, do some
computation according to A and replace A with B. I am trying to do this
within a while loop but I have no idea how to plug s///g into this
loop. Can anyone offer some clue?

Here is an example: In string 'a123ba456b', the pattern to find is
a(.*?)b and this string needs to be processed as 'a(1)ba(2)b', meaning
that the occurance of '123' is recorded and put back into the original
string.

Thanks a million!

Rick
 
G

Gunnar Hjalmarsson

Rick said:
I need to loop over a string to find some pattern A, do some
computation according to A and replace A with B. I am trying to do this
within a while loop but I have no idea how to plug s///g into this
loop. Can anyone offer some clue?

Here is an example: In string 'a123ba456b', the pattern to find is
a(.*?)b and this string needs to be processed as 'a(1)ba(2)b', meaning
that the occurance of '123' is recorded and put back into the original
string.

my $string = 'a123ba456b';
my (%vars, $i);
( my $newstring = $string ) =~ s{a(.*?)b}{
$vars{ ++$i } = $1;
"a($i)b";
}eg;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top