in reply to Unexpected results from a regex replacement

Hi

Can you post a full code snippet with __DATA__ tags that show this effect? My test on 5.6.1 doesn't show the behavior that you're seeing.

foreach my $outdata ( <DATA> ) { print "Init: $outdata\n"; $outdata =~ s{<cfmail}{<!--- <cfmail}g; $outdata =~ s{</cfmail>}{</cfmail> --->}g; print "Final: $outdata\n\n"; } __DATA__ <cfmail to="#to_address#"> </cfmail>
The results were

Init: <cfmail to="#to_address#"> Final: <!--- <cfmail to="#to_address#"> Init: </cfmail> Final: </cfmail> --->
So it's hard to see where the your issue is coming from. My only assumption is that your regex code is in a loop that runs the 25 times that the comment characters get repeated.

- j

Replies are listed 'Best First'.
Re^2: Unexpected results from a regex replacement
by yacoubean (Scribe) on Nov 10, 2004 at 22:14 UTC
    Ok, here's the entire sub:
    sub find_replace { my $filename = shift; open (my $infile, "$dir/$filename") or die "Can't open file: $!"; my $outdata = ""; while (<$infile>) { $outdata .= $_; $outdata =~ s{../CLRIS/}{}g; $outdata =~ s{../../menu/}{}g; $outdata =~ s{../../Images}{Images}g; $outdata =~ s{<cfmail}{<!--- <cfmail}g; $outdata =~ s{</cfmail>}{</cfmail> --->}g; } close $infile; open (my $outfile, "+>$dir/$filename") or die "Can't open file: $! +"; print $outfile "$outdata"; close $outfile; }
    The first three replacements work correctly.

    P.S. I gave the before/after data in my first post. I'm using ActivePerl 5.8.4.810.
      The problem is that each time you append the new line to $outdata, and then run your replacements against the entire text (not just the newly added line). To fix it, either run your replacements once outside of the loop or run them only on the new line. Actually, I would suggest another approach without the loop.
      sub find_replace { my $filename = shift; open (my $infile, "$dir/$filename") or die "Can't open file: $!"; local $/ = undef; my $outdata = <$infile>; close $infile; $outdata =~ s{../CLRIS/}{}g; $outdata =~ s{../../menu/}{}g; $outdata =~ s{../../Images}{Images}g; $outdata =~ s{<cfmail}{<!--- <cfmail}g; $outdata =~ s{</cfmail>}{</cfmail> --->}g; open (my $outfile, "+>$dir/$filename") or die "Can't open file: $! +"; print $outfile "$outdata"; close $outfile; }
      Oh, while I'm looking at it, I suspect you don't actually mean s{../CLRIS/}{}g;. It seems much more likely that you mean s{\.\./CLRIS/}{}g;