1

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?

Ivan
  • 163
  • 1
  • 12
  • 2
    You mean the [comma operator](http://blogs.perl.org/users/steven_haryanto/2012/09/the-comma-operator.html)? You can use it as an alternate statement separator which is what seems to be happening here, but it's not the best idea. Use `;` and a new statement instead. – tadman Jan 29 '20 at 20:06

3 Answers3

5

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--)
choroba
  • 231,213
  • 25
  • 204
  • 289
  • 2
    I prefer the longer version (using a block with one statement per line). If you crammed 2 statements into the “if”, chances are high that you will need to add more. The longer form is more clear and maintainable. – Timur Shtatland Jan 29 '20 at 21:36
  • 1
    @Timur Shtatland, Even worse is that it hides a flow control change (`next`). – ikegami Jan 30 '20 at 14:47
3

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
Grinnz
  • 9,093
  • 11
  • 18
2

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.

Rob Sweet
  • 184
  • 8