@resuna You are technically correct about the C grammar: A block ("compound statement") is just a type of statement. But that's not how I tend to think about it. In practice, it's more like "an if
body can be either a single statement or multiple statements wrapped in braces" or even "the braces after if
are optional if there's just a single statement in them". (Treating {}
as special punctuation is also how most formatting styles work.)
However, that is not how Perl works. if (foo) bar();
is a syntax error. Perl requires a full block as the body of control structures like if
, while
, etc. Similarly, { bar(); } if (foo);
is a syntax error because, in the modifier syntax, the thing before if
cannot be a statement.
The correct syntactic forms for Perl are:
if ( <expression> ) <block>
<expression> if <expression> ;
Instead of if
you can also have unless
, while
, or until
. (There is also for
, but its syntax is a bit more involved.)
So why does Perl require a full block after a control structure? Because it avoids the "dangling else" ambiguity typically found in C-like languages (in if (a) if (b) f(); else g();
, which if
does the else
belong to?) and because it avoids an error where you start out with a simple statement in an if
, but then add a second statement without adding braces:
if (cond)
foo();
bar(); // oops, bar() is called unconditionally
This kind of bug has caused security vulnerabilities (CVE-2014-1266 or the "goto fail" bug, https://en.wikipedia.org/wiki/Unreachable_code#goto_fail_bug) and Perl is immune to it, by design.
There is no reason for the latter two to even exist.
Sometimes they make code more readable. For example, many people think the following code reads quite naturally:
return $x
unless $x < 0;
...
push @ results, $record
if $record->matches($query);
And just about every data type, constant, control structure, or other semantic object in Perl has at least as many gratuitously different syntaxes for exactly the same thing.
Yeah, nah. I don't think that's true and the examples you've given so far are still just simple syntax (or syntax errors in some cases 😃). This is the stuff you'd expect to encounter in week 1 or 2 of learning Perl. We're not even close to "language lawyer" territory yet.