Search code examples
perlperlsyn

Meaning of the perl syntax construction involving a comma


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?


Solution

  • 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.