Warm tip: This article is reproduced from stackoverflow.com, please click
perl perlsyn

Meaning of the perl syntax construction involving a comma

发布于 2020-04-10 16:05:59

I've encountered a piece of code in a book that looks like this:

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

I've got no clue what does the comma (",") between $anotherVar+1 and before next do. How is this syntax construction called and is it even correct?

Questioner
Ivan
Viewed
60
Rob Sweet 2020-02-02 01:30

Consider the following code:

$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";

The output is as follows:

With comma: 1 1
With semicolon: 2 1

A comma is similar to a semicolon, except that both sides of the command are treated as a single statement. This means that in a situation where only one statement is expected, both sides of the comma are evaluated.