Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Interpolating variables in a loop

Status
Not open for further replies.

domster

Programmer
Oct 23, 2003
30
0
0
GB
Hi, I'm having trouble with this code:

while ($data =~ s/<tag>/<tag id="$id">/g) {
$id++;
}

the problem is that the updated $id doesn't get substituted in the loop, although the variable does get updated. I thought that so long as you don't use the o qualifier, the regex will recompile every time it's run. How can I get around this? Thansk in advance for your help.

Dom
 
to clarify, if I run the code on the following strings, one after another:

<tag>a tag</tag><tag>another tag</tag>

<tag>yet another tag</tag>

I get:

<tag id="1">a tag</tag><tag id="1">another tag</tag>

<tag id="2">yet another tag</tag>

ie it seems the substitution happens for all matches in the string, then $id is incremented; I was expecting $id would be incremented every time a string was substituted.

Dom
 
try taking out the /g modifier, and move the regex along the string, or parse the file using a parser from search.cpan.org, and run the regex on each node

HTH
--Paul
 

i would not assume that the internal looping of a regex can not be used in a while loop.
 
I was wondering if it might be a buffering problem, try turning the buffer on or off using
Code:
$| = 1;
It's default is set to '0', I know this is primarily for screen output, it may affect how your loop is dealt with in the program. Alternatively there may be some similar method for altering the buffering of the program...though not sure what!
 
$id=1;
$a="<tag>a tag</tag><tag>another tag</tag>";
$a =~ s/^|$/'/g;
$a =~ s/<tag>/<tag id='.\$id++.'>/g;
$b= eval $a;
print $b,"\n";
 
OK, i was wrong about looping, PaulTEG was correct:

$a="<tag>a tag</tag><tag>another tag</tag>";
$id=1;
while ($a =~ s/<tag>/<tag id=$id>/) {
++$id;
}

The "pos" description provided my illumination.
'g' for 'm': while ($a =~ m/<tag>/g)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top