gpt4 book ai didi

perl - "do something"的语法如果 "condition"

转载 作者:行者123 更新时间:2023-12-02 09:12:09 25 4
gpt4 key购买 nike

自从我使用 Perl 以来,我就知道使用 if 的三种方法。

if(condition){
"do this";
"do that";
}
"do this" if condition; 
condition ? "do this" : "or this";

但是我认为最后两个只能在你只有一个命令要执行的情况下使用。然而最近我了解到,当使用第二个选项时,您可以通过用逗号分隔它们来执行多个命令。

perl -e '$count++, $var="Hello" if 4 < 5; print "COUNT: $count, VAR: $var\n"'
COUNT: 1, VAR: Hello

我意识到用例有限,但它激发了我的兴趣。我试图查看 perldoc 以找到记录此行为的语法,但看不到任何解释如果用逗号分隔可以使用多个命令的内容。

这种行为是特定于以这种方式使用 if 语句,还是由于 Perl 的某些其他特性而起作用?如果有人可以向我指出任何关于该行为的文档,那就太好了。

最佳答案

Is this behavior specific to using the if statement in this way, or does it work due to some other feature of Perl?

,这不是特定于后修复if。事实上,每个语句都可以是几件事的列表。有时这是有道理的,有时则没有。

print 1, 2;
print(1, 2);
print( (1, 2) );
print( ( (1), (2) ) );

这些都是相同的,因为在 Perl 中列表将被展平。同样,您可以在那里进行函数调用。

foo(), bar();
( foo(), bar() );

结合律并不总是像此处那样清晰,因此在某些情况下使用括号是有意义的。

但是,如果您想要一个后缀 if 和一个 block ,您应该使用一个 block 。你在标题中回答了你自己的问题,真的。使用 do 语言结构。

do {
foo();
bar();
} if $condition;

当然,如果这样做,您也可以使用适当的 if block 。

关于perl - "do something"的语法如果 "condition",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50929049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com