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

I used code similar to this:
$_=q{<>^}; for $i qw(<> >^){ /$i/ and print "$&\n" }
...and wanted to have 2 answers, but got only 1. It seems that I need to use \Q$i\E, why? "^" is not at the beginning of regex. And it seems that <> characters are quoted, if I use quotemeta, but why they are meta?

Replies are listed 'Best First'.
Re: Can't find list of metacharacters
by Kenosis (Priest) on Oct 05, 2014 at 19:51 UTC

    Consider the following:

    use strict; use warnings; local $_ = q{<>^}; for my $i (qw(<> >^)) { /\Q$i/p and print "${^MATCH}\n"; }

    Output:

    <> >^

    Remember that "^" can also be used to negate a class match in addition to denoting a match at the beginning of a line, e.g., /^[^aeiou]/i (no vowels at the beginning of a line). Both "<" and ">" are metacharacters. See this Extended regex sequences section.

    Hope this helps!

      Thanks
Re: Can't find list of metacharacters
by LanX (Saint) on Oct 05, 2014 at 20:47 UTC
    This

    > for $i qw(<> >^){

    should be deprecated by now, please always put parentheses around your list.

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

Re: Can't find list of metacharacters
by ikegami (Patriarch) on Oct 06, 2014 at 05:59 UTC
    Note that for $i qw(<> >^) { ... } isn't valid Perl syntax. A bug in Perl used to treat it equivalent to for $i (qw(<> >^)) { ... }, but that has been fixed.
    >perl -e"for my $i qw( a b ) { }" syntax error at -e line 1, near "$i qw( a b )" Execution of -e aborted due to compilation errors.
      Thanks for discussion and explanations, but I haven't understand why it is a bug - not using parentheses, a from when? And then - why?
Re: Can't find list of metacharacters
by Anonymous Monk on Oct 05, 2014 at 22:06 UTC
    And it seems that <> characters are quoted, if I use quotemeta, but why they are meta?

    quotemeta doesn't bother being smart about what it escapes, because it doesn't need to, and because a list of metacharacters might not be portable across different versions of Perl. quotemeta just escapes everything that might be special, even if that character isn't necessarily special at that point in the regex.

    Always using quotemeta / \Q...\E is a good habit to get into when interpolating variables into regexes. I'd only not use them when I want the string in the variable to be interpreted as a regex, or when I know the variable I'm interpolating contains no special characters (something like /^[A-Za-z_0-9]*$/).