in reply to Stupid question about regex with string followed variable in replacement

> But is there any way to do that another way? Maybe there is some character, that could be used as separator?

Perl always allows curlies to surround the symbol's name (or expression) following sigils!

So

$txt =~ s/test/${foo}bar/;

instead of

$txt =~ s/test/$foobar/;

HTH =)

Cheers Rolf

( addicted to the Perl Programming Language)

UPDATE

Documentation wasn't easy to find:

from perldata#Scalar value constructors

As in some shells, you can enclose the variable name in braces to disambiguate it from following alphanumerics (and underscores). You must also do this when interpolating a variable into a string to separate the variable name from a following double-colon or an apostrophe, since these would be otherwise treated as a package separator:
  • Comment on Re: Stupid question about regex with string followed variable in replacement ( ${varname} )
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: Stupid question about regex with string followed variable in replacement
by Anonymous Monk on May 19, 2013 at 22:27 UTC

    Thank you very much! :)

    Work like a charm for both problems :)

      In the spirit of TIMTOWTDI, you could also disable metacharacter processing using "\Q..\E":
      my $txt = '1,2'; $txt=~ s/(\d+)\,(\d+)/$1\Q0\E,$2/;
      This converts the "1" to "10".

      Unfortunately, simply escaping like "\0" does not work for many cases, because many escape sequences have special meaning .. Eg: \0 starts an octal sequence. See "perldoc perlrebackslash"

                   "I'm fairly sure if they took porn off the Internet, there'd only be one website left, and it'd be called 'Bring Back the Porn!'"
              -- Dr. Cox, Scrubs

        In this case I wouldn't use '\Q' at all, since it has an effect while '\E' is quite neutral!

        DB<100> $var=666 => 666 DB<101> "$var\Efoo" => "666foo" DB<102> "$var\Ef\Eoo" => "666foo"

        Anyway the use case is restricted to interpolation like in qq{} or regex.

        Curlies can be used for any variable.

        Cheers Rolf

        ( addicted to the Perl Programming Language)

        Thank you for your reply as well :)

        Quite interesting way to avoid that problem.

        Btw, I was using escape characters before, but like you pointed it's not working for many cases, so I finally decide to ask for Perl Wisdom to do it right :)

      You're welcome! =)

      BTW it's not a stupid questions, many allowed (though exotic) variable names are only accessible if surrounded by curlies ...

      Cheers Rolf

      ( addicted to the Perl Programming Language)

        And huge thanks for update! :)

        I was searching for something like that before asking my question and even after your answer without any useful results (most likely I just wrongly formulate my request).