Why "?:" operator cannot return list?

127 Views Asked by At

Why ?: operator can not return list?

my $hash =  {
    ...
    ($row->active?checked=>1:()),
};

The DOC say nothing about scalar or list context

UPD
Another example:

@list =  2,3;         # CORRECT
@list =  1? 2,3 : (); # Syntax error

Why first is OK, but second is not? It seems there should not be the problem for perl to just propagate 2,3 to the outer context;

2

There are 2 best solutions below

0
On BEST ANSWER

The problem is that , and => (the list separators) have lower precedence than ?: and =.

So it's not a question about whether perl is passing the right hand side of = as a list or scalar. It's a syntax error because @list=1?2 and 3:() are handled as separate items of a list, each containing half a ?: statement which is not allowed.

5
On

This has nothing to do with context. You need to put parenthesis around the middle part for Perl to properly parse your syntax.

my $hash = { ( 1 ? ( checked => 1 ) : () ), };

Without those, there is a syntax error.

syntax error at /home/simbabque/code/scratch/scratch.pl line 109, near "checked =>"