in reply to Re: Syntax error - beginner question
in thread Syntax error - beginner question

Ay yi yi...as a beginner at Perl that just makes my brain hurt. ;-)

Can someone parse that out, or give me a link to where it's explained. Thanks
  • Comment on Re: Re: Syntax error - beginner question

Replies are listed 'Best First'.
Re^3: Syntax error - beginner question
by Aristotle (Chancellor) on Jan 11, 2004 at 20:17 UTC

    This all stuff used in many languages and not specific to Perl.

    The ternary operator works in the form of $condition_expr ? $true_expr : $false_expr. The conditional expression (here: ($X < 10)) is evaluated first. If it tests true, the $true_expr is then evaluated and its result is returned. Likewise with $false_expr if the conditional expression evaluated to false.

    Then you have a shortcut operator $foo op= $bar;, where op stands for a mathematical, bitwise, or logical operator - here +. It is a shortcut for $foo = $foo op $bar;. So $foo += $bar; is a concise way to say "increase $foo by $bar".

    So a sort-of token-by-token translation of the expression in my post to English would read something like "$Y is increased by either (if $X is less than 10) 2000 or by 1900 (otherwise)".

    Obviously the first time you see such a construct it'll look strange. And it certainly isn't the point to use them wherever possible. Brevity is not a goal for its own sake. But assuming familiarity with such constructs, readability is maximized by choosing the briefest possible form that follows the structure of a natural language sentence describing the same thought. In this case this is statement is closest to how I'd explain the intent: "add the century depending on the year". It expresses exactly that in a straightforward manner: there's one condition, one addition/assignment, and the numbers, without any artificial extra verbiage.

    Makeshifts last the longest.

Re: Re: Re: Syntax error - beginner question
by Theo (Priest) on Jan 11, 2004 at 21:49 UTC
    I know that feeling! It's a common brain-response when getting questions answered here. I highly recommend getting a copy of Learning Perl. Basic stuff like this is covered well with many exercises to give you a feel for how to use the language.

    -Theo-
    (so many nodes and so little time ... )