http://qs321.pair.com?node_id=536515

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

Monks,

I noticed that when I match a '{' at the end of a regular expression and use strict and warnings, Perl does not give an error.
I am not sure if this is normal.

jkva

Update : This is perl, v5.8.4 built for i386-linux-thread-multi.

Replies are listed 'Best First'.
Re: Perl Regular Expression inconsistency
by japhy (Canon) on Mar 14, 2006 at 13:31 UTC
    The only time '{' needs to be escaped is when it is followed by a set of digits, followed by an optional comma and more digits, followed by a closing '}'. If you don't want that sequence of characters to be interpreted as a quantifier, all you need to do is escape the leading '{'. (This is ignoring places where {...} is part of an escaped expression like \p{Xyz} and \N{CHARACTER}.)

    '{' is only a metacharacter in a very specific circumstance. You almost never need to backslash it in a regex.


    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: Perl Regular Expression inconsistency
by GrandFather (Saint) on Mar 14, 2006 at 11:09 UTC

    I see the same behaviour with AS Perl v5.8.7. What is even more interesting is that there is some odd inconsistency in the way different meta characters are handled:

    • /{/ no error
    • /}/ no error
    • /]/ no error
    • /[/ error
    • /)/ error
    • /(/ error

    DWIM is Perl's answer to Gödel
      Well, it doesn't seem that odds to me. [ starts a range, so it must be escaped; ( starts a selection, so it must be escaped; { doesn't mean anything special, so it hasn't to be escaped.
        Doesn't '{' start a {} quantifier?

        By that logic an unmatched ')' doesn't mean anything so shouldn't need to be escaped, yet it generates an error.

        japhy's eplanation is satisfying for unmatched '{' and '}' and extends to an unmatched ']' too. Why not extend the argument to an unmatched ')'? Is that so much more likely a "You Really Mean That?" error that it's worth special casing?


        DWIM is Perl's answer to Gödel