Khatri has asked for the wisdom of the Perl Monks concerning the following question:

$t = "abc"; $b = "x"; $l = "xyzabcdef"; $l =~ s/can I use $t here ? /can I use $b here ?/g;
Although I know I can do s/\babc\b/\bx\b/g; but is it possbile using $variables as shown above?

Replies are listed 'Best First'.
Re: Can I Use Variables In A Regex?
by jZed (Prior) on Oct 30, 2005 at 00:52 UTC
    I'm not trying to be sarcastic, but : what happened when you tried? Wouldn't it be easier to just type that all out and then print the value of $l to see if it's what you expect?

    The short answer is, yes you can do things like that. If the part that you are matching contains regex characters like periods and parens, you will need to use quotemeta() to escape them.

Re: Can I Use Variables In A Regex?
by pg (Canon) on Oct 30, 2005 at 02:33 UTC

    As jZed said, had you tried, you would have found out yourself.

    use Data::Dumper; use strict; use warnings; my $t = "abc"; my $b = "x"; my $l = "xyzabcdef"; $l =~ s/$t/$b/g; print $l;

    This prints:

    xyzxdef

    Make it simple, obviously it works.

Re: Can I Use Variables In A Regex?
by dragonchild (Archbishop) on Oct 30, 2005 at 02:12 UTC
    $l =~ s/\b$t\b/$b/eg;

    The 'e' is required to treat the replacement as Perl code and not a literal string. You don't want the \b's in the replacement because the replacement isn't a regex - it's normally a literal string. You can chain 'e' so that the first evaluation would produce Perl code that would, itself, be evaluated.

    This is all explained in the relevant page at http://perldoc.perl.org. (Scroll down a bit to find the s/// section.)


    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
      The 'e' is required to treat the replacement as Perl code and not a literal string.
      Except that perl treats it as a double-quoted string which interpolates, so the /e isn't required in this case.

      Dave.