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

Hello. I tried to avoid some parenthesis and have got some problems.
Firstly, I wanted to write this code in fashion of ternary operator:
perl -le '$_ = "a"; print do { if( length ){ "A" } else{ "B" } };'
OUTPUT:
A
There is with "ternary":
perl -le '$_ = "a"; print length ? "A" : "B" '
OUTPUT:
Warning: Use of "length" without parentheses is ambiguous at -e line 1 +. Use of ?PATTERN? without explicit operator is deprecated at -e line 1. Search pattern not terminated or ternary operator parsed as search pat +tern at -e line 1.
I forgot that 'length' is unary operator with higher precedence, so it interpret following '?' as matching parens. Same if I would write: 'print length // "A" ' - error, when 'print length || "A" ' - is ok.
So I tried to avoid 'length' to interpret '?' as regex in this way:
perl -le '$_ = "a"; print length . '' ? "A" : "B" '
But it still outputs:
Use of ?PATTERN? without explicit operator is deprecated at -e line 1. Search pattern not terminated or ternary operator parsed as search pat +tern at -e line 1.
Concatenation point has higher precedence than unary 'length' so I think 'length' should give its value which will be concatenated with empty line, and later ternaty op., and later - 'print'.
If I use '+ 0' instead, I got warning of ambiguity (but '+' can't start a regex, and for me seems that there is no ambiguity):
perl -le '$_ = "a"; print length + 0 ? "A" : "B" '
Warning: Use of "length" without parentheses is ambiguous at -e line 1 +. A

Replies are listed 'Best First'.
Re: parsing 'length ...'
by Athanasius (Archbishop) on Feb 24, 2016 at 15:38 UTC

    Hello rsFalse,

    perl -le '$_ = "a"; print length . '' ? "A" : "B" '

    The one-liner terminates at the second '. Try using "" for the empty string instead of '' here:

    1:34 >perl -le "$_ = 'a'; print length . '' ? 'A' : 'B'" A 1:34 >

    (but my single and double quotes are reversed because I’m on Windows.)

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: parsing 'length ...'
by Anonymous Monk on Feb 24, 2016 at 16:19 UTC
    The clue is in this warning:
    Warning: Use of "length" without parentheses is ambiguous
    So...
    $ perl -le '$_ ="a"; print length() ? "A" : "B"' A $
Re: parsing 'length ...'
by kcott (Archbishop) on Feb 25, 2016 at 06:17 UTC

    G'day rsFalse,

    A couple of tips from someone who's fallen foul of both the problems you've encountered on more than one occasion:

    1. Whenever I get a "Use of "whatever" without parentheses is ambiguous" warning, adding the parentheses, rather than casting around for some other workaround, is generally the easiest solution.
    2. Quotes within one-liners are problematic. Consider using the various q{}, qq{}, etc. Quote-Like Operators instead of literal quotation marks.

    — Ken