This is ok:
if ($some_var==$some_value) {}
This is ok too:
print "hello" if ($some_var==$some_value);
But this raises 开发者_开发技巧an error:
if ($some_var==$some_value) print "some_message";
Why must 'if' clause in Perl come with either curly brackets or nothing?
To avoid the well-known problem in compiler construction known as a "dangling else". See http://en.wikipedia.org/wiki/Dangling_else
Perl has a rather complex syntax and is rather difficult to parse. I gather that curly brackets were made mandatory following an if clause so as to remove an ambiguity and make Perl code easier to parse.
That's how the perl
syntax is defined. The if (expr) BLOCK
syntax requires a block, not a statement. See perlsyn
("Compound statements" section).
Excerpt:
The if statement is straightforward. Because BLOCKs are always bounded by curly brackets, there is never any ambiguity about which if an else goes with.
if ($some_var==$some_value);
is not "ok too" when I try it (nor did I expect it to be).
Why is a BLOCK required, and a plain EXPR not allowed? Because that's how Larry wanted it.
I don't know about the curlies, but Larry spoke mentioned that the parens could have been made optional. I believe he decided against it to keep the code readable.
I believe it simply isn't supported, this however is: print "some_message" if($some_var == $some_value);
精彩评论