Ivan
Ivan

Reputation: 163

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?

Upvotes: 1

Views: 386

Answers (3)

Rob Sweet
Rob Sweet

Reputation: 184

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.

Upvotes: 2

choroba
choroba

Reputation: 242103

The comma operator is described in 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 which changes the flow of the program.

Basically, this is a shorter way of writing

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

The comma can be used in a similar way in C, where you can find it often in for loops:

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

Upvotes: 5

Grinnz
Grinnz

Reputation: 9231

The comma is 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://learn.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

Upvotes: 3

Related Questions