Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List context and the comma operator in Perl

Having some significant confusion about what it means to "evaluate in list context", specifically related to the comma operator. In the linked perlop doc, it says: In list context, it's just the list argument separator, and inserts both its arguments into the list. However, the code

@y = 9, 8, 7, 6;
say @y, ', ', scalar @y;

gives output 9, 1. This respects the fact that, when used as a binary operator on scalar values (?), the comma operator , has lower precedence that the assignment = operator. But since I'm assigning to the list @y, shouldn't the right hand side of the assignment be evaluated in list context and, by the above quote, treat the comma simply as a separator?

I suspect that I just don't truly understand what it "evaluate in list context" means, precisely...

like image 812
fmg Avatar asked Dec 13 '25 11:12

fmg


1 Answers

The problem has nothing to do with context.[1] It's a precedence issue.

Assignment has higher precedence than comma, so

my @y = 9, 8, 7, 6;

means

( my @y = 9 ), 8, 7, 6;

but you want

my @y = ( 9, 8, 7, 6 );

Note that the parens do nothing but override precedence.

Warnings would have caught this. Always use use strict; use warnings; or equivalent!


I suspect that I just don't truly understand what it "evaluate in list context" means, precisely...

Each operator decides what to do and what to return based on the context in which they are evaluated.

It does not, however, change how code is parsed.


  1. my @y on the left is enough to cause the list assignment to be used, and is thus enough to cause the RHS to be evaluated in list context. See Scalar vs List Assignment Operator.
like image 103
ikegami Avatar answered Dec 15 '25 00:12

ikegami