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

Hi monks, I've run into trouble matching a pattern in a variable if it's starting with a caret:
$p = $s = "^xxx"; print "$p has $s\n" if $s =~ /$p/; #does not print
What's a good way to not have the caret be taken for an anchor? Thanks.

Replies are listed 'Best First'.
Re: Matching patterns containing a caret
by almut (Canon) on Apr 26, 2009 at 09:54 UTC

    You need to quotemeta the string in $p:

    $p = $s = "^xxx"; print "$p has $s\n" if $s =~ /\Q$p/; #does print

    (Depending on whether there's something else not to be quoted after the $p (in your real case), you might also want \E to end the quoting, e.g. /\Q$p\E|foo/)

Re: Matching patterns containing a caret
by stephanm (Sexton) on Apr 26, 2009 at 11:49 UTC
    Thanks, guys.

    The \Q solution makes the most sense in my case because I dont need to check if there happens to be a caret in front.

    Much appreciated.

Re: Matching patterns containing a caret
by jwkrahn (Abbot) on Apr 26, 2009 at 15:58 UTC
    print "$p has $s\n" if 0 == index $s, $p;
Re: Matching patterns containing a caret
by janusmccarthy (Novice) on Apr 26, 2009 at 10:05 UTC
    Escape it by placing a \ before the caret.
    $p = $s = "\^xxx"; print "$p has $s\n" if $s =~ /$p/; #does not print
      $p = $s = "\^xxx";

      You probably meant

      $s = "^xxx"; $p = '\^xxx'; # or "\\^xxx" ...

      (a backslash in a double-quoted string just escapes the next char...)

        Why worry about quoting constructs? qr// has worked very well for ages:

        my $p = qr/\^xxx/;