Why do Perl control statements require braces?

后端 未结 8 1338
挽巷
挽巷 2021-02-07 00:05

This may look like the recent question that asked why Perl doesn\'t allow one-liners to be \"unblocked,\" but I found the answers to that question unsatisfactory because they ei

8条回答
  •  忘掉有多难
    2021-02-07 00:10

    One reason could be that some styles dictate that you should always use braces with control structures, even for one liners, in order to avoid breaking them later, e.g.:

    if (condition) 
       myObject.doSomething();
    else 
       myObject.doSomethingElse();
    

    Then someone adds something more to the first part:

    if (condition)
       myObject.doSomething();
       myObject.doSomethingMore(); // Syntax error next line
    else 
       myObject.doSomethingElse();
    

    Or worse:

    if (condition)
       myObject.doSomething();
    else 
       myObject.doSomethingElse();
       myObject.doSomethingMore(); // Compiles, but not what you wanted.
    

    In Perl, these kinds of mistakes are not possible, because not using braces with control structures is always a syntax error. In effect, a style decision has been enforced at the language syntax level.

    Whether that is any part of the real reason, only Larry's moustache knows.

提交回复
热议问题