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

Hi monks,

I've a question regarding the use of brackets in a ternary expression below:
# without brackets print $lines > 1 ? 'plural' : 'singular'; # with brackets print ($lines > 1) ? 'plural' : 'singular';
I thought I needed the brackets to get the particular line of code to work as expected but it turns out that I'm able to get the code to print 'plural' when $lines is greater than 1 and 'singular' when $lines equals 1.

Why aren't the brackets neccessary?

I look forward to reading your replies :)

kiat

Replies are listed 'Best First'.
Re: What difference do the brackets make?
by stephen (Priest) on Dec 11, 2002 at 08:13 UTC

    Welcome to the wonderful world of operator precedence.

    Instead of simply parsing operators from right to left or left to right, Perl (and most other programming languages) uses a scheme where certain operators (such as '<') are parsed before certain others (such as the '?:' conditional operator). See 'perldoc perlop' for the entire list of operators and their precedence.

    That's why

    print 3 + 2 * 5;
    prints 13, not 25. It reads it as 3+(2*5), not (3+2)*5.

    In your case, since '<' has a higher precedence than '?:', the '$lines > 1' statement is parsed first without the help of brackets.

    That's not to say that you don't need the brackets there. Perl doesn't need them, but frequently we programmers need them to keep track of what's going on.

    stephen

Re: What difference do the brackets make?
by jsprat (Curate) on Dec 11, 2002 at 08:07 UTC
    The precedence of '>' is higher than that of the ternary operator, so the expression "$lines > 1" is evaluated before the "?:".

    For a complete list of operator associativity and precedence, see perlop.

Re: What difference do the brackets make?
by bronto (Priest) on Dec 11, 2002 at 09:17 UTC

    I ran your code through Deparse, and this is what I got:

    $ perl -MO=Deparse,-p print $lines > 1 ? 'plural' : 'singular'; print ($lines > 1) ? 'plural' : 'singular'; __END__ print((($lines > 1) ? 'plural' : 'singular')); (print(($lines > 1)) ? '???' : '???'); - syntax OK

    While in the first line all that follows print is print's argument, in the second line only $lines > 1 is the argument

    So, besides the precedence rules cited by jsprat and stephen, you should remember another rule I found somewhere in the Camel Book:

    if it looks like a function, it is a function

    that is: if you enclose something in parentheses just after a function, e.g. print, what's enclosed in parentheses is considered that function's argument

    Ciao!
    --bronto

    # Another Perl edition of a song:
    # The End, by The Beatles
    END {
      $you->take($love) eq $you->make($love) ;
    }

Re: What difference do the brackets make?
by tadman (Prior) on Dec 11, 2002 at 09:13 UTC
    In your example, '>' has a higher precendence than '?:', as documented in perlop. You don't technically need the brackets in this case, but there are examples of where they are vitally important:
    print $lines = $some_value? 'true' : 'false';
    In this case, since '=' has a lower precendence, what actually gets evaluated is:
    print $lines = ($some_value? 'true' : 'false');
    This means $lines gets assigned a value of either 'true' or 'false'.
    print ($lines = $some_value)? 'true' : 'false';
    This actually assigns the proper value to $lines and prints accordingly.

    For the sake of clarity, sometimes it's a good idea to just put the brackets in there anyway. Some editors allow you to bounce between bracket pairs, which can help when navigating complex conditions.

    Update:
    As Anarion is quick to point out, that last example is actually defective. It should be:
    print (($lines = $some_value)? 'true' : 'false');
    I think it was being parsed as something like:
    (print $lines = $some_value)? 'true' : 'false';
Re: What difference do the brackets make?
by Anarion (Hermit) on Dec 11, 2002 at 09:15 UTC
    That's not the same, try this code:
    perl -le 'print print(0>1) ? "true ???!!!" : "is false"'

    and then

    perl -le 'print print 0>1 ? "true ???!!!" : "is false"'


    On the first, ? evaluates the return value of print, the second the condition 0>1.

    $anarion=\$anarion;

    s==q^QBY_^=,$_^=$[x7,print
(vocabulary is important) Re: What difference do the brackets make?
by PodMaster (Abbot) on Dec 11, 2002 at 18:53 UTC
    I see no brackets. My assembler teacher does this too, and it's such a big deal

    [ ] Brackets
    { } Braces
    ( ) Parenthesis

    See in perl, [ 1, 2 ] is an array reference, and  { 1, 2} is a hash reference, and  ( ) are neither.

    BTW - i'm sure you're aware by now that `perldoc perlop' discusses operators & precedence.

    Vocabulary is important, even though everybody can see that you have no brackets in your question, but what will happen when you're talking to somebody on the phone, and you say brackets, and they say What?!??? ;)


    MJD says you can't just make shit up and expect the computer to know what you mean, retardo!
    ** The Third rule of perl club is a statement of fact: pod is sexy.

      Your absolutely right sauoq ref: Oxford University

      [ ] Square brackets
      { } Braces or Curly brackets
      ( ) Brackets or round brackets
      < > Angle brackets

      Purely practical. Try describing this expression down the telephone to someone having to say "left parethesis" and "right parenthesis" every time.

      (((a + b) *((c+d)*e))**(f/(1/2)))


      Okay you lot, get your wings on the left, halos on the right. It's one size fits all, and "No!", you can't have a different color.
      Pick up your cloud down the end and "Yes" if you get allocated a grey one they are a bit damp under foot, but someone has to get them.
      Get used to the wings fast cos its an 8 hour day...unless the Govenor calls for a cyclone or hurricane, in which case 16 hour shifts are mandatory.
      Just be grateful that you arrived just as the tornado season finished. Them buggers are real work.

        No need for parenthesis to describe that expression. Just say:

        a plus b pause times pause c plus d pause times pause e pause all of it to the power of 2 f.

        Alternatively:

        The product of the sum of a and b, the sum of c and d, and of e, and that to the power 2 times f.

        ;-)

        Abigail

      I think "brackets" means "parantheses" in the UK. This is a global community afterall.

      -sauoq
      "My two cents aren't worth a dime.";