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

Meaning of the perl syntax construction involving a comma

我在一本书中遇到过这样一段代码:

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

我不知道 $anotherVar+1next 之间的逗号 (",") 有什么作用。这种语法结构是如何调用的,它是否正确?

逗号是an operator, in any context. In list context where it's usually seen, it is one way to concatenate values into a list. Here it is being used in scalar context, where it runs the preceding expression, the following expression, and then returns the following expression. This is a holdover from how it works in C and similar languages, when it's not an argument separator; see https://docs.microsoft.com/en-us/cpp/cpp/comma-operator?view=vs-2019.

my @stuff = ('a', 'b'); # comma in list context, forms a list and assigns it
my $stuff = ('a', 'b'); # comma in scalar context, assigns "b"
my $stuff = 'a', 'b'; # assignment has higher precedence
                      # assignment done first then comma operator evaluated in greater context

perlop. You can use it to separate commands, it evaluates its left operand first, then it evaluates the second operand. In this case, the second operand is next 中描述了逗号运算符,它改变了程序的流程。

基本上,这是一种较短的写法

if ($var eq "...") {
    $var = $anotherVar + 1;
    next
}

逗号在 C 语言中的用法与此类似,您经常会在 for 循环中找到它:

for (i = 0, j = 10; i < 10; i++, j--)

考虑以下代码:

$x=1;
$y=1;

$x++ , $y++ if 0; # note the comma! both x and y are one statement
print "With comma: $x $y\n";

$x=1;
$y=1;

$x++ ; $y++ if 0; # note the semicolon! so two separate statements

print "With semicolon: $x $y\n";

输出结果如下:

With comma: 1 1
With semicolon: 2 1

逗号类似于分号,只是命令的两边都被视为一个语句。这意味着在只需要一个语句的情况下,逗号两边都会被评估。