in reply to Re: Unexpected results from a regex replacement
in thread Unexpected results from a regex replacement

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.

Replies are listed 'Best First'.
Re^3: Unexpected results from a regex replacement
by Eimi Metamorphoumai (Deacon) on Nov 10, 2004 at 22:23 UTC
    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;