in reply to Second Time Replace Regex

How about something like:

my $file_name = ...; my $file; { open(my $fh, '<', $file_name) or die("Unable to open input file: $!\n"); local $/; $file = <$fh>; } my ($P) = $file =~ /A(.*?)B/ or die("Unable to find 'P'\n"); $file =~ s/(C.*?)\Q$P\E/$1Q/g; { open(my $fh, '>', $file_name) or die("Unable to open output file: $!\n"); print $fh $file; }

Update: Added \Q...\E.

Replies are listed 'Best First'.
Re^2: Second Time Replace Regex
by JediWizard (Deacon) on Dec 02, 2005 at 22:37 UTC

    Correct me if I'm wrong but . . . My understanding is that \Q and \E would not be needed in the regex if you quotemeta $P, or vise versa (quotemeta is not needed if you use \Q .. \E). From quotemeta:

    Returns the value of EXPR with all non-"word" characters backslashed. (That is, all characters not matching /A-Za-z_0-9/ will be preceded by a backslash in the returned string, regardless of any locale settings.) This is the internal function implementing the \Q escape in double-quoted strings.

    If EXPR is omitted, uses $_ .

    They say that time changes things, but you actually have to change them yourself.

    —Andy Warhol

      I accidently updated prematurely. You saw bad code I had there for 5s. quotemeta plus \Q...\E would indeed give incorrect results.