in reply to Operator precedence of unary plus (Bug or Feature)

Perl has to apply heuristics, opting to guess what the programmer intended, instead of having a defined parsing rule, and sticking to it.

Since it's common for programmers to put spaces on both sides of binary operators, and also common to not have a space between a unary operator and its argument, Perl chooses to parse print $q + 4*5 as if the + were a binary operator, and print $q +4*5 as if the + were a unary operator.

Replies are listed 'Best First'.
Re^2: Operator precedence of unary plus (Bug or Feature)
by LanX (Saint) on Feb 05, 2012 at 12:17 UTC
    I think this special parsing is restricted to print and say.

    The plus in this snippet: "5   +6" will in most other cases be interpreted as a binary operator, no matter how many whitespaces.

    Cheers Rolf

      I think this special parsing is restricted to print and say.
      Perl does not have to apply heuristics if there's only one way of parsing it. In most cases, the only way to parse the plus sign will either be as binary operator, or as a unary operator.
      The plus in this snippet: "5 +6" will in most other cases be interpreted as a binary operator, no matter how many whitespaces.
      package Foo; sub bar {say "[@_]"} package main; bar Foo + 6;
      This will print [Foo 6] no matter how many whitespace you use around the +. This actually surprised me, I would have expected Perl to apply the same heuristics as the OP encountered.
        >This actually surprised me, I would have expected Perl to apply the same heuristics as the OP encountered.

        I remember discussing here that "print FILEHANDLE" has a special magic different from normal "indirect object" syntax.

        but the parsing of bar Foo +6; is not really as dangerous as print $x +6 is.

        If Foo was a constant, any association to the package Foo would be overwritten.

        DB<140> package Foo; sub bar { print __PACKAGE__."::bar => [@_]\n"} DB<141> package main; sub bar { print __PACKAGE__."::bar => [@_]\n"} DB<142> bar Foo+6; Foo::bar => [Foo 6] DB<143> use constant "Foo" =>5 DB<144> bar Foo+6; main::bar => [11]

        But in the OP $q doesn't hold a filehandle.

        UPDATE: Maybe the whole confusion started, when variables for filehandles were introduced.

        Cheers Rolf