in reply to Help with regex using variables

$find="C:\\Dir1\\Dir2\\Dir3"; $replace=''; $var = "C:\\Dir1\\Dir2\\Dir3\\KeepMe"; $var =~ s/$find/$replace/eeg; print "\$var: $var\n";

The first line interpolates the double quoted string, converting "\\" to '\'.

The fourth line also interpolates the string.

Try using either $find='C:\\Dir1\\Dir2\\Dir3'; or better yet use $find = qr/C:\\Dir1\\Dir2\\Dir3/;.

Naked blocks are fun! -- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re^2: Help with regex using variables
by haukex (Archbishop) on May 16, 2023 at 07:24 UTC
    Try using either $find='C:\\Dir1\\Dir2\\Dir3';

    No, that's the exact same as "C:\\Dir1\\Dir2\\Dir3", since single-quoted strings still interpolate a few characters, backslashes being one of them.

    The fourth line also interpolates the string.

    Not only does it interpolate, it will also interpret any characters special to regexes as such. Your qr// suggestion is good, as an alternative I would suggest s/\Q$find\E/$replace/ to escape the string (see quotemeta).