What does "if (1)" do?
Solution 1
Technically, the if (1)
does nothing interesting, since it's an always-executed if-statement.
One common use of an if (1)
though is to wrap code you'd like to be able to quickly disable, say for debugging purposes. You can quickly change an if (1)
to if (0)
to disable the code.
Solution 2
Yes, 1 is treated as true, so the block after if (1)
is always executed.
From perldoc
The number 0, the strings '0' and "" , the empty list () , and undef are all false in a boolean context. All other values are true.
Solution 3
1
is indeed being treated as a boolean value in this case, which always evaluates to true
.
This is basically an if
statement which always passes (making it unnecessary in the first place).
Solution 4
When in doubt, use Deparse
:
$ perl -MO=Deparse -e'if (1) {}'
do {
()
};
-e syntax OK
Solution 5
It runs the code block. It's equivalent to:
{
...
}
Added by ikegami:
No, it's not.
{ ... }
is a "bare loop", a loop that executes only once. It is affected by next
, last
and redo
.
if (1) { ... }
is not a loop. It is not affected by next
, last
and redo
.
>perl -E"for (1..3) { say $_; if (1) { next; } say $_; }"
1
2
3
>perl -E"for (1..3) { say $_; { next; } say $_; }"
1
1
2
2
3
3
However, they are similar in that both create a lexical scope.
user2521358
Updated on June 25, 2022Comments
-
user2521358 almost 2 years
What does the syntax
if (1) {}
do?
I can't find documentation for this syntax and 1 is not being treated as a boolean. Am I right?.