Tuesday, May 1, 2012

Perl: while with no conditional


stackoverflow 上面有人問了有趣的問題

According to the doc, the while statement executes the block as long as the expression
 is true. I wonder why it becomes an infinite loop with an empty expression

while () { # infinite loop
 ...
}

Is it just inaccuracy in the doc?

Perl: while with no conditional

我們可以用

perl -MO=Deparse [Perl program]

B::Deparse module  - Perl compiler backend to produce perl code

來分析語法上的正確性


B::Deparse is a backend module for the Perl compiler that generates perl source code, based on the internal compiled structure that perl itself creates after parsing a program. The output of B::Deparse won't be exactly the same as the original source, since perl doesn't keep track of comments or whitespace, and there isn't a one-to-one correspondence between perl's syntactical constructions and their compiled form, but it will often be close. When you use the -p option, the output also includes parentheses even when they are not required by precedence, which can make it easy to see if perl is parsing your expressions the way you intended.
While B::Deparse goes to some lengths to try to figure out what your original program was doing, some parts of the language can still trip it up; it still fails even on some parts of Perl's own test suite. If you encounter a failure other than the most common ones described in the BUGS section below, you can help contribute to B::Deparse's ongoing development by submitting a bug report with a small example.





以下幾個分析 ...

$ perl -MO=Deparse -e 'while (){}'
while (1) {
    ();
}
-e syntax OK

$ perl -MO=Deparse -e 'for (){}'
syntax error at -e line 1, near "()"
-e had compilation errors.

$ perl -MO=Deparse -e 'for (()){}'
foreach $_ (()) {
    ();
}
-e syntax OK

$ perl -MO=Deparse -e 'for ((<>)){}'
foreach $_ (<ARGV>) {
    ();
}
-e syntax OK

$ perl -MO=Deparse -e 'for(;;){}'
while (1) {
    ();
}
-e syntax OK



最後一個例子是 Brain D Foy 給出的

No comments:

Post a Comment