涉及逗号的 perl 语法结构的含义

Iva*_*van 1 perl perlsyn

我在一本书中遇到过一段代码,如下所示:

#for (some_condition) {
#do something not particularly related to the question
$var = $anotherVar+1, next if #some other condition with $var
#}
Run Code Online (Sandbox Code Playgroud)

我不知道$anotherVar+1next之前的逗号 (",") 是什么意思。这种语法结构是如何调用的,它甚至正确吗?

cho*_*oba 5

逗号运算符在perlop 中描述。您可以使用它来分隔命令,它首先评估其左操作数,然后评估第二个操作数。在这种情况下,第二个操作数是下一个改变程序流程的操作数。

基本上,这是一种较短的写作方式

if ($var eq "...") {
    $var = $anotherVar + 1;
    next
}
Run Code Online (Sandbox Code Playgroud)

逗号可以在 C 中以类似的方式使用,您可以在 for 循环中经常找到它:

for (i = 0, j = 10; i < 10; i++, j--)
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢较长的版本(使用每行一个语句的块)。如果您在“if”中塞入两条语句,那么您很可能需要添加更多语句。较长的形式更加清晰且可维护。 (2认同)