Earlier today I posted a similar question, whose solution leads to a new problem, -,-
Well, the story is that I want Perl to capture comments from a text, store them in array, and replace them with new numbered comments, say, for original $txt:
//first comment
this is a statement //second comment
//third comment
more statements //fourth comment
I wanna push the 4 comments into an array, and get new $txt like:
//foo_0
this is a statement //foo_1
//foo_2
more statements //foo_3
I tried the following Perl:
$i=0;
$j=0;
#while ($txt =~ s/(\/\/.*?\n)/\/\/foo_$i\n/gs) {
#while ($txt =~ s/(\/\/.*?\n)/\/\/foo_$i\n/s) {
#foreach ($txt =~ s/(\/\/.*?\n)/\/\/foo_$i\n/gs) {
foreach ($txt =~ s/(\/\/.*?\n)/\/\/foo_$i\n/s) {
if(defined $1) {
push (@comments, $1);
print " \$i=$i\n";
$i++
}
print " \$j=$j\n";
$j++;
}
print "after search & replace, we have \$txt:\n";
print $txt;
foreach (0..$#comments) {
print "\@comments[$_]= @comments[$_]";
}
In it, I tried the "while/foreach (... s///gs)" in four flavors, but none of them actually did what I want.
The "foreach" statement will work on the text only once; and more worse, the "while" statement will enter endless loop, seems like the new "//foo_xx" stuff is put back into the string for further search operations, making it an infinite iteration. It's so strange that such a seemingly simple search-and-replace mechanism would get mired in endless loop, or there're some obvious tricks that I don't know of?
BTW, I already went through the post by highsciguy . For him, "simply replacing while with foreach in the above code will do"; but for me the foreach just does not work, I don't know why.
Anyone get any ideas in helping me with this? Thanks~