in reply to Problem using value of variable in a regular expression

A string used in a regex is used as a regular expression.

I guess you've understood this, but your attempt to escape the star didn't work:

$ perl -wE 'say "\*E"' *E

The double-quoted string ate the backslash, the regex just sees *E.

There are several solutions:

# ugly, but works: my $failmsg = "\\*E"; if (/$failmsg/) { ... } # nicer, since you don't have to do the escaping yourself $failmsg = '*E'; if (/\Q$failmsg\E/) { ... } # if you want to quote regular expressions, do this: $failmsg = qr{\*E}; if ($_ =~ $failmsg) { ... }

This last solution is nice because it accepts modifiers, so for example if you want to do a case-insensitive match, you can write $failmsg = qr{\*E}i;.

Perl 6 - links to (nearly) everything that is Perl 6.

Replies are listed 'Best First'.
Re^2: Problem using value of variable in a regular expression
by JavaFan (Canon) on Jul 30, 2010 at 10:38 UTC
    And some other ways:
    my $failmsg = '\*E'; # Single quotes prevent interpolation my $failmsg = '[*]E'; # Character class makes it not special. my $failmsg = "*E"; if (index($_, $failmsg) >= 0) # Don't use a regexp.
Re^2: Problem using value of variable in a regular expression
by Anonymous Monk on Jul 30, 2010 at 10:37 UTC
    moritz, Thanks for the quick reply. But, what surprises me is double-quotes eating up the backslash. This is very arbitrary, unintuitive(at least to me), and also undesirable. Do you know if this is documented anywhere? Thanks for all the help.

      It's not undesirable at all. In double quotes, the backslash is indicates the start of an escape allowing "\n" to mean newline, "\"" to mean a double quote, etc. Double quotes are documented in perlop.

      You're just using the wrong tool.

      $failmsg = qr/\*E/;
        Thanks for the reply. I wasn't aware of the interpolation in perl. The problem with searching a solution for such a query is that one has to know the name of the concept behind the issue(here it is "interpolation") to get quickly to the answer. But then if one knew the concept, he/she wouldn't be facing the problem in the first place.
      Documented in various places. perlop, sections Quote-Like Operators and Gory details of parsing quoted constructs, and perldata, section Scalar value constructors.