Why do Perl control statements require braces?

后端 未结 8 1176
挽巷
挽巷 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:16

    One problem with braceless if-else clauses is they can lead to syntactic ambiguity:

    if (foo)
        if (bar)
           mumble;
        else
           tumble;
    

    Given the above, under what condition is tumble executed? It could be interpreted as happening when !foo or foo && !bar. Adding braces clears up the ambiguity without dirtying the source too much. You could then go on to say that it's always a good idea to have the braces, so let's make the language require it and solve the endless C bickering over whether they should be used or not. Or, of course, you could address the problem by getting rid of the braces completely and using the indentation to indicate nesting. Both are ways of making clear, unambiguous code a natural thing rather than requiring special effort.

提交回复
热议问题