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

I'm trying to check if $after contains $scur:

if ($after =~ "$scur") { do something; }

Problem is, $scur is a dollar sign ($). The conditional is returning true no matter what; my suspicion is that the $ is being inserted into the regular expression literally (making it m/$/ . . . which would always match). What can I do?

Replies are listed 'Best First'.
Re: Regex Error
by japhy (Canon) on May 20, 2004 at 01:50 UTC
    Sounds like you don't even need a regex.
    if (index($after, $scur) > -1) { # $after contains the text in $scur }
    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;
Re: Regex Error
by beth (Scribe) on May 20, 2004 at 01:09 UTC

    A variable can contain a regular expression, metacharacters and all, so you are correct about what perl is doing here: it's interpreting the dollar sign as the indicator for end-of-line.

    You can get the behavior you want by using \Q (quote) and \E (end, I guess). \E is optional:

    if ($after =~ /\Q$scur/){ ...

    You can read more about this in perldoc perlre.

    (2004-05-20 fixed typo that swapped \U for \E)
Re: Regex Error
by Nkuvu (Priest) on May 20, 2004 at 01:01 UTC
    I think you want \Q and \E:

    #!/usr/bin/perl use strict; my $cur = "\$foo"; my $after = "This is a \$foo test"; print "Match: '$after' contains '$cur'\n" if ($after =~ /\Q$cur\E/);
Re: Regex Error
by pbeckingham (Parson) on May 20, 2004 at 00:35 UTC

    Try the following:

    if ($after =~ /$scur/) { do something; }
    or if you want a literal $ in the pattern:
    if ($after =~ /\$scur/) { do something; }

Re: Regex Error
by rjahrman (Scribe) on May 20, 2004 at 00:42 UTC
    I've already tried the first way (I also tried $after =~ $scur).

    And I don't want a literal dollar sign . . . the contents of $scur could change.

    ?

      If you've tried the first way and it didn't work, then I suspect that $after and/or $scur do not contain quite the data you expect. Can you confirm this? Are there newlines in either? Is case an issue? How about using:

      my $pattern = "\\" . $cur; if ($after =~ /$pattern/) { do something; }